diff --git a/ASSETS.md b/ASSETS.md index 5bebefae63..3233c99d0e 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -345,6 +345,9 @@ Generated-in-code art is original and has no file to list. This covers the defau | `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | +| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` | +| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` | +| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` | ## Assets embedded by the PDF backend diff --git a/Cargo.lock b/Cargo.lock index 941e205f3b..7a1e533f06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1940,6 +1940,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + [[package]] name = "gif" version = "0.14.2" @@ -2233,7 +2243,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -2609,14 +2619,14 @@ dependencies = [ "bytemuck", "byteorder-lite", "color_quant", - "gif", + "gif 0.14.2", "image-webp", "moxcms", "num-traits", "png 0.18.1", "tiff", - "zune-core", - "zune-jpeg", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", ] [[package]] @@ -2837,7 +2847,7 @@ dependencies = [ "bumpalo", "flate2", "float-cmp", - "gif", + "gif 0.14.2", "image-webp", "imagesize 0.14.0", "indexmap", @@ -2852,7 +2862,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -4380,12 +4390,15 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" dependencies = [ + "gif 0.13.3", + "image-webp", "log", "pico-args", "rgb", "svgtypes 0.15.3", "tiny-skia", "usvg 0.45.1", + "zune-jpeg 0.4.21", ] [[package]] @@ -5490,7 +5503,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -6169,7 +6182,7 @@ dependencies = [ "tiff", "vectorcraft-color", "vectorcraft-geom", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -6195,6 +6208,7 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "hayro-jpeg2000", "image", "kurbo 0.13.1", "log", @@ -6375,7 +6389,7 @@ name = "vectorcraft-render" version = "0.19.0" dependencies = [ "flate2", - "gif", + "gif 0.14.2", "image", "jpeg-encoder", "log", @@ -6487,6 +6501,7 @@ dependencies = [ "kurbo 0.13.1", "serde", "serde_json", + "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", @@ -7951,19 +7966,34 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + [[package]] name = "zune-core" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + [[package]] name = "zune-jpeg" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ - "zune-core", + "zune-core 0.5.3", ] [[package]] diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index e76e67ba5b..fbec570112 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -386,10 +386,22 @@ impl CornerSource { #[serde(default)] pub struct PatternBrush { pub side: Node, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub outer_corner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub inner_corner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_swatch: Option, /// What the outer corners take when there is no `outer_corner` art. Without art or a source, /// they take the `inner_corner` art. #[serde(skip_serializing_if = "Option::is_none")] @@ -400,8 +412,16 @@ pub struct PatternBrush { pub inner_source: Option, #[serde(skip_serializing_if = "Option::is_none")] pub start: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub end: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_swatch: Option, /// Scale in percent. pub scale: f64, /// Space between tiles in percent of the tile width. @@ -422,12 +442,22 @@ impl Default for PatternBrush { fn default() -> Self { Self { side: defaults::stitch_tile(), + side_frame: None, + side_swatch: None, outer_corner: None, + outer_corner_frame: None, + outer_corner_swatch: None, inner_corner: None, + inner_corner_frame: None, + inner_corner_swatch: None, outer_source: None, inner_source: None, start: None, + start_frame: None, + start_swatch: None, end: None, + end_frame: None, + end_swatch: None, scale: 100.0, spacing: 0.0, fit: PatternFit::Stretch, @@ -500,6 +530,14 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn valid_tile_frame(frame: Rect) -> bool { + [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) + && frame.width().is_finite() + && frame.height().is_finite() + && frame.width() > 1e-9 + && frame.height() > 1e-9 +} + impl Colorization { /// A Hue Shift key colour that isn't a colour (components out of reach) becomes black. fn sanitize(&mut self) { @@ -600,6 +638,11 @@ impl Brush { BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); + for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { + if frame.is_some_and(|f| !valid_tile_frame(f)) { + *frame = None; + } + } p.colorization.sanitize(); } BrushKind::Bristle(b) => { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 28bbcda752..6362c8da8d 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -561,6 +561,43 @@ fn pattern_corner_source_none_leaves_that_kind_of_corner_empty() { assert!((outer == plain && inner == saved) || (inner == plain && outer == saved), "only the corners set to None are empty"); } +#[test] +fn pattern_without_start_tile_runs_side_to_path_start() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = Some(rect_art(20.0, 4.0)); + } + let with_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(with_start[0].geometric_bounds().unwrap().width(), 20.0); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = None; + } + let without_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_start.len(), 10); + assert!(near(without_start[0].geometric_bounds().unwrap().x0, 0.0, 1e-6)); + assert!(near(without_start[0].geometric_bounds().unwrap().width(), 10.0, 1e-6)); +} + +#[test] +fn pattern_without_end_tile_runs_side_to_path_end() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = Some(rect_art(20.0, 4.0)); + } + let with_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert!(with_end.iter().any(|n| near(n.geometric_bounds().unwrap().width(), 20.0, 1e-6))); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = None; + } + let without_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_end.len(), 10); + assert!(near(without_end.last().unwrap().geometric_bounds().unwrap().x1, 100.0, 1e-6)); +} + #[test] fn pattern_corner_sources_round_trip_and_stay_out_of_brushes_without_them() { let saved = serde_json::to_value(pattern_brush(PatternFit::Stretch, true)).unwrap(); diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index d66d5679fb..78c2f547f3 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -247,6 +247,16 @@ fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> (b.width() > 1e-9).then_some((a, b)) } +/// Orient a tile's repeat frame with its art. The frame can be smaller than the art. +fn oriented_tile(art: &Node, frame: Option, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> { + let (node, bounds) = oriented(art, Direction::LeftToRight, flip_along, flip_across)?; + let Some(frame) = frame else { return Some((node, bounds)) }; + let x = if flip_along { (-frame.x1, -frame.x0) } else { (frame.x0, frame.x1) }; + let y = if flip_across { (-frame.y1, -frame.y0) } else { (frame.y0, frame.y1) }; + let frame = Rect::new(x.0, y.0, x.1, y.1); + (frame.width() > 1e-9 && frame.height() > 1e-9).then_some((node, frame)) +} + /// Piecewise-linear map from art x (offset from the art's left edge) to arc length. #[derive(Clone, Copy, Debug)] pub(crate) struct AlongMap { @@ -800,13 +810,13 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { } pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { - let orient = |n: &Node| oriented(n, Direction::LeftToRight, pb.flip_along, pb.flip_across); - let Some(side) = orient(&pb.side) else { return vec![] }; + let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); + let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; let k = weight * pb.scale.max(1.0) / 100.0; - let outer = pb.outer_corner.as_ref().and_then(orient); - let inner = pb.inner_corner.as_ref().and_then(orient); - let start = pb.start.as_ref().and_then(orient); - let end = pb.end.as_ref().and_then(orient); + let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); + let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); + let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); + let end = pb.end.as_ref().and_then(|n| orient(n, pb.end_frame)); let tw = side.1.width() * k; let gap = tw * pb.spacing.max(0.0) / 100.0; // Each kind of corner takes its own art, else its source, else the other kind's art. diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8201b8b97f..64f42f25b9 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -149,11 +149,20 @@ impl IccProfile { /// Device values (RGB / CMYK / Gray, 0..1) → sRGB. pub fn to_srgb(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + let mut src = [0.0f32; 4]; + let channels = self.channels(); + src.get_mut(..channels)?.iter_mut().zip(v.iter()).for_each(|(dst, value)| *dst = *value); + self.to_srgb_into(src.get(..channels)?, intent) + } + + /// Convert an exact-width device pixel using the cached transform and stack storage. + pub fn to_srgb_into(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + if v.len() != self.channels() { + return None; + } let xf = self.to_xf(intent)?; - let mut src = v.to_vec(); - src.resize(self.channels(), 0.0); let mut dst = [0.0f32; 3]; - xf.transform(&src, &mut dst).ok()?; + xf.transform(v, &mut dst).ok()?; Some(dst.map(|x| x.clamp(0.0, 1.0))) } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 8379858745..b754e0d565 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -110,6 +110,12 @@ pub fn hit_test_visible(doc: &Document, p: Point, opt: HitOptions) -> Option bool) -> Option { + hit_test_skipping(doc, p, opt, skip, false) +} + /// The object of `selected` (topmost first) whose own art lies under `p` where a clipping mask /// hides it: a clip group (or a layer with a clipping mask) holding it doesn't clip to `p`. A /// click there hits nothing ([`hit_test`]), so the selection tools grab the selection by that @@ -538,20 +544,15 @@ fn hit_children( } /// The order a click at `p` tries the children of `parent` in, front first: their stacking order -/// from the top, except that in an Intertwine group the members drawn over the others at `p` -/// come first (from the top among them too). +/// from the top, except that in an Intertwine group the members are tried in the order they are +/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]). fn hit_order<'a>(parent: &Node, children: &'a [std::sync::Arc], p: Point) -> impl Iterator + 'a { - let over: Vec = if matches!(parent.kind, NodeKind::Intertwine { .. }) { - let contains = |a: &vectorcraft_geom::PathData| fill_contains(&a.to_bezpath(), vectorcraft_geom::FillRule::NonZero, p); - (0..children.len()).rev().filter(|i| children.get(*i).and_then(|c| crate::intertwine::over_area(c)).is_some_and(contains)).collect() - } else { - vec![] - }; - let rest = (0..children.len()).rev().filter({ - let over = over.clone(); - move |i| !over.contains(i) - }); - over.into_iter().chain(rest) + let mut order: Vec = (0..children.len()).rev().collect(); + if matches!(parent.kind, NodeKind::Intertwine { .. }) { + let tier = |i: usize| children.get(i).map_or(0, |c| crate::intertwine::tier_at(c, p)); + order.sort_by_cached_key(|i| std::cmp::Reverse((tier(*i), *i))); + } + order.into_iter() } /// A click on the strokes of a path or compound path `n` along `bp`: what any visible stroke diff --git a/crates/doc/src/intertwine.rs b/crates/doc/src/intertwine.rs index e22ccbbaf3..8a6ab6786f 100644 --- a/crates/doc/src/intertwine.rs +++ b/crates/doc/src/intertwine.rs @@ -1,36 +1,51 @@ //! Object › Intertwine: objects that pass over and under each other. //! //! An Intertwine group ([`NodeKind::Intertwine`]) keeps its members as they are, in their own -//! stacking order. A member can be drawn over the other members in part of the group: that area -//! is the member's [`crate::node::NodeExtras::intertwine`], in document coordinates. The group -//! draws (and exports, and is hit) as its live expansion ([`expand`]): the members, then, for -//! each member with an area, a copy of it clipped to that area. Where several members are drawn -//! over the others in one place, the upper one in the stacking order ends on top. +//! stacking order. A member can be drawn over other members in part of the group, at a tier: the +//! area of tier 1 is the member's [`crate::node::NodeExtras::intertwine`], and the areas of tiers 2 +//! and up are its [`crate::node::NodeExtras::intertwine_tiers`], in document coordinates. In each +//! place the members are drawn by their tier there (0 outside their areas), and members of one +//! tier in their stacking order, so any order of the members can be set for each overlap area. +//! The group draws (and exports, and is hit) as its live expansion ([`expand`]): the members, +//! then, tier by tier, a copy of each member with an area of that tier clipped to it. //! //! The members stay editable, and Release gives them back as they were (the areas let go). //! Behaviour: . use std::sync::Arc; -use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, Point}; use crate::{Node, NodeId, NodeKind}; -/// The area where `n` is drawn over the other members of its Intertwine group (empty: nowhere). -pub fn over_area(n: &Node) -> Option<&PathData> { - n.extras().intertwine.as_deref().filter(|a| !a.is_empty()) +/// The areas where `n` is drawn over other members of its Intertwine group, each with its tier +/// (1 and up); empty ones are left out. +pub fn tier_areas(n: &Node) -> impl Iterator { + let e = n.extras(); + e.intertwine + .as_deref() + .map(|a| (1, a)) + .into_iter() + .chain(e.intertwine_tiers.iter().enumerate().map(|(k, a)| (k + 2, a))) + .filter(|(_, a)| !a.is_empty()) } -/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then each -/// member with an area drawn over the others, as a clip group of that area around a copy of it -/// (ids 0: generated art). +/// The tier `n` is drawn at at `p`: the highest tier whose area holds `p` (0: none does). +pub fn tier_at(n: &Node, p: Point) -> usize { + tier_areas(n).filter(|(_, a)| fill_contains(&a.to_bezpath(), FillRule::NonZero, p)).map(|(t, _)| t).max().unwrap_or(0) +} + +/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then, for +/// each tier from 1 up, each member with an area of that tier, as a clip group of that area +/// around a copy of it (ids 0: generated art). pub fn expand(children: &[Arc]) -> Vec { let mut out: Vec = children.iter().map(|c| plain(c)).collect(); - for c in children { - let Some(area) = over_area(c) else { continue }; - if !c.visible { - continue; - } + let mut over: Vec<(usize, usize, &PathData)> = + children.iter().enumerate().filter(|(_, c)| c.visible).flat_map(|(i, c)| tier_areas(c).map(move |(t, a)| (t, i, a))).collect(); + over.sort_by_key(|(t, i, _)| (*t, *i)); + for (_, i, area) in over { + let Some(c) = children.get(i) else { continue }; let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area.clone(), rule: FillRule::NonZero, live: None, clipping: true, guide: false }); clip.appearance = crate::Appearance::default().into(); let mut copy = plain(c); @@ -40,11 +55,13 @@ pub fn expand(children: &[Arc]) -> Vec { out } -/// `n` without its Intertwine area (the expansion is plain art). +/// `n` without its Intertwine areas (the expansion is plain art). fn plain(n: &Node) -> Node { let mut n = n.clone(); - if n.extras().intertwine.is_some() { - n.extras_mut().intertwine = None; + if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() { + let mut e = n.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); } n } @@ -88,6 +105,28 @@ mod tests { assert_eq!((out[2].id, children[1].id), (NodeId(0), NodeId(0)), "generated art has no ids of its own"); } + #[test] + fn copies_are_drawn_tier_by_tier() { + let over = || shapes::rectangle(Rect::new(5.0, 0.0, 10.0, 10.0)); + // The lower member at tier 2, the upper one at tier 1: the lower one ends on top. + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 5.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b)]; + assert_eq!((tier_at(&kids[0], Point::new(7.0, 5.0)), tier_at(&kids[1], Point::new(7.0, 5.0))), (2, 1)); + assert_eq!(tier_at(&kids[0], Point::new(2.0, 5.0)), 0); + let out = expand(&kids); + assert_eq!(out.len(), 4, "both members, then the copy of tier 1, then the one of tier 2"); + assert!(out.iter().all(|n| n.extras().intertwine.is_none() && n.extras().intertwine_tiers.is_empty()), "the expansion is plain art"); + let copied = |n: &Node| match &n.kind { + NodeKind::Group { children, clip: true } => children[1].path_data().cloned(), + k => panic!("a clip group: {k:?}"), + }; + assert_eq!(copied(&out[2]).as_ref(), kids[1].path_data()); + assert_eq!(copied(&out[3]).as_ref(), kids[0].path_data()); + } + #[test] fn a_hidden_member_is_not_drawn_over_the_others() { let mut a = (*square(1, 0.0)).clone(); diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 1b234c2122..304b7fede4 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -237,13 +237,28 @@ mod tests { fn mesh_insert_and_remove_lines() { let mut m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); - let i = m.add_lines_at(Point::new(30.0, 60.0)).unwrap(); + let i = m.add_lines_at(Point::new(30.0, 60.0), 0.0).unwrap(); assert_eq!((m.rows, m.cols), (2, 2)); assert!(m.points[i].p.distance(Point::new(30.0, 60.0)) < 0.5, "{:?}", m.points[i].p); assert!(m.remove_point_lines(i)); assert_eq!((m.rows, m.cols), (1, 1)); } + /// A point outside the mesh within the tolerance locates the nearest point of its edge. + #[test] + fn mesh_locate_within_reaches_the_edge() { + let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let p = Point::new(102.0, 30.0); + assert_eq!(m.locate(p), None); + assert_eq!(m.locate_within(p, 1.0), None); + let (r, c, u, v) = m.locate_within(p, 3.0).unwrap(); + assert_eq!((r, c), (0, 1)); + assert_eq!(u, 1.0, "on the right edge"); + let q = m.eval(r, c, u, v); + assert!(q.distance(Point::new(100.0, 30.0)) < 1e-6, "{q:?}"); + assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0))); + } + /// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB. #[test] fn a_cmyk_mesh_mixes_its_inks() { diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index f72dd548cc..e6ba1656f1 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -592,12 +592,21 @@ impl GradientMesh { /// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh). pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> { + self.locate_within(p, 0.0) + } + + /// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the + /// patch and local (u, v) of the nearest point of the mesh's edge. + pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> { if !self.is_valid() { return None; } let bp = self.outline().to_bezpath(); if bp.winding(p) == 0 { - return None; + if tol.is_nan() || tol <= 0.0 { + return None; + } + return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); } const N: usize = 16; let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); @@ -634,6 +643,30 @@ impl GradientMesh { Some((r, c, u, v)) } + /// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its + /// boundary patch and local (u, v). + fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; + let (rows, cols) = (self.rows as usize, self.cols as usize); + let mut best: Option<(f64, usize, usize, f64, f64)> = None; + let mut take = |e: CubicBez, at: (usize, usize, Option, Option)| { + let n = e.nearest(p, 1e-9); + if best.is_none_or(|b| n.distance_sq < b.0) { + let (r, c, u, v) = at; + best = Some((n.distance_sq, r, c, u.unwrap_or(n.t), v.unwrap_or(n.t))); + } + }; + for c in 0..cols { + take(self.edge_u(0, c), (0, c, None, Some(0.0))); + take(self.edge_u(rows, c), (rows - 1, c, None, Some(1.0))); + } + for r in 0..rows { + take(self.edge_v(r, 0), (r, 0, Some(0.0), None)); + take(self.edge_v(r, cols), (r, cols - 1, Some(1.0), None)); + } + best + } + /// Index of the mesh point within `tol` of `p`. pub fn point_near(&self, p: Point, tol: f64) -> Option { self.points @@ -721,9 +754,10 @@ impl GradientMesh { self.cols += 1; } - /// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index. - pub fn add_lines_at(&mut self, p: Point) -> Option { - let (r, c, u, v) = self.locate(p)?; + /// Mesh tool click: add a row and a column through `p` (inside the mesh, or outside within + /// `tol` of its edge, through the nearest point of the edge). Returns the new point index. + pub fn add_lines_at(&mut self, p: Point, tol: f64) -> Option { + let (r, c, u, v) = self.locate_within(p, tol)?; let mut rr = r; let mut cc = c; let row_new = v > 0.02 && v < 0.98; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a971a383b5..bf9259943b 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -253,6 +253,9 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); + if e.intertwine_tiers.capacity() > 0 { + b += ALLOC + e.intertwine_tiers.capacity() * size_of::() + e.intertwine_tiers.iter().map(path_bytes).sum::(); + } b += e.objects_on_path.as_deref().map_or(0, |o| { ALLOC + size_of::() + o.members.capacity() * size_of::() }); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 633f9b6967..93145985be 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -44,6 +44,11 @@ pub struct NodeExtras { /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, /// filled non-zero) where this object is drawn over the group's other members. pub intertwine: Option>, + /// Object › Intertwine: as a member of an Intertwine group, the areas (document coordinates, + /// filled non-zero) where this object is drawn over members that are themselves drawn over + /// others there. Item `k` is the area of tier `k + 2`; [`NodeExtras::intertwine`] is tier 1 + /// (see [`crate::intertwine`]). + pub intertwine_tiers: Vec, /// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults). pub live_paint_gaps: Option>, /// Object › Objects on Path: the group's path and the objects attached to it (see @@ -76,6 +81,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { perspective: None, dimension: None, intertwine: None, + intertwine_tiers: Vec::new(), live_paint_gaps: None, objects_on_path: None, colorize: None, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index fcf2c9429d..e5c98886a2 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -496,8 +496,13 @@ 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. - if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) { - area.transform(a); + if let Some(e) = self.extras_if_any() { + if let Some(area) = e.intertwine.as_mut() { + area.transform(a); + } + for area in &mut e.intertwine_tiers { + area.transform(a); + } } } @@ -686,6 +691,12 @@ impl Node { /// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient /// stops or a colorized image. Hidden objects show none. pub fn shows_transparency(&self) -> bool { + self.shows_transparency_with(&|_| true) + } + + /// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize` + /// accepts it, for files that write some colorized images in their colorize paint (EPS). + pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { use vectorcraft_color::Paint; let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible); @@ -693,14 +704,14 @@ impl Node { && (self.opacity < 1.0 || self.blend != BlendMode::Normal || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) - || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some()) + || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) || effects(&self.appearance.effects) || self .appearance .items .iter() .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) - || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency()))) + || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) } } diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index b4cc7b0722..df675580e2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -484,6 +484,23 @@ fn objects_are_read_within_the_node_budget() { assert!(with_node_budget(3, read).is_ok()); } +/// An Intertwine member's areas of tier 2 and up are written and read back, and each one counts +/// against [`with_node_budget`] as an object does, so a file of many empty areas is refused. +#[test] +fn intertwine_tiers_are_read_within_the_node_budget() { + let mut n = Node::group(NodeId(1), vec![]); + let area = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + n.extras_mut().intertwine_tiers = vec![PathData::default(), area]; + let json = serde_json::to_string(&n).unwrap(); + assert!(json.contains("\"intertwine_tiers\""), "{json}"); + let read = || serde_json::from_str::(&json); + assert_eq!(with_node_budget(3, read).unwrap(), n, "the object and its two areas fit a budget of three"); + let why = with_node_budget(2, read).unwrap_err().to_string(); + assert!(why.contains("more than 2 objects"), "{why}"); + let plain = serde_json::to_string(&Node::group(NodeId(1), vec![])).unwrap(); + assert!(!plain.contains("intertwine_tiers"), "an object without tiers writes none: {plain}"); +} + /// #3587: fields read before an object's `type` are buffered value by value within /// [`with_buffered_value_budget`], each counted once: a group read back from the buffer buffers /// its own fields again without counting them twice. VectorCraft writes `type` first, which diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 76d4c3c14a..3456b359e2 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -46,6 +46,7 @@ impl Serialize for Node { e.perspective.is_none(), e.dimension.is_none(), e.intertwine.is_none(), + e.intertwine_tiers.is_empty(), e.live_paint_gaps.is_none(), e.objects_on_path.is_none(), e.colorize.is_none(), @@ -85,6 +86,7 @@ impl Serialize for Node { field!("perspective", &e.perspective); field!("dimension", &e.dimension); field!("intertwine", &e.intertwine); + field!("intertwine_tiers", &e.intertwine_tiers); field!("live_paint_gaps", &e.live_paint_gaps); field!("objects_on_path", &e.objects_on_path); field!("colorize", &e.colorize); @@ -123,11 +125,39 @@ pub fn with_node_budget(max: usize, f: impl FnOnce() -> T) -> T { /// each counts once, and the id usually comes first, before the node's children are read. fn counted_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { let id = NodeId::deserialize(d)?; + count_one()?; + Ok(id) +} + +/// Count one object against [`with_node_budget`]. +fn count_one() -> Result<(), E> { if let Some((left, max)) = NODES_LEFT.get() { - let left = left.checked_sub(1).ok_or_else(|| serde::de::Error::custom(format!("the document has more than {max} objects")))?; + let left = left.checked_sub(1).ok_or_else(|| E::custom(format!("the document has more than {max} objects")))?; NODES_LEFT.set(Some((left, max))); } - Ok(id) + Ok(()) +} + +/// A member's Intertwine areas of tier 2 and up, each counting against [`with_node_budget`] as +/// an object does: a compressed file of repeated empty areas stays small while they take memory +/// once read. +fn counted_tiers<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + struct Tiers; + impl<'de> serde::de::Visitor<'de> for Tiers { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list of areas") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::new(); + while let Some(area) = seq.next_element::()? { + count_one()?; + out.push(area); + } + Ok(out) + } + } + d.deserialize_seq(Tiers) } /// How a [`Node`] is read: the flat field list of the file format. Fields move into the node @@ -186,6 +216,8 @@ pub(super) struct NodeWire { dimension: Option>, #[serde(default)] intertwine: Option>, + #[serde(default, deserialize_with = "counted_tiers")] + intertwine_tiers: Vec, #[serde(default)] live_paint_gaps: Option>, #[serde(default)] @@ -215,6 +247,7 @@ impl From for Node { perspective: w.perspective, dimension: w.dimension, intertwine: w.intertwine, + intertwine_tiers: w.intertwine_tiers, live_paint_gaps: w.live_paint_gaps, objects_on_path: w.objects_on_path, colorize: w.colorize, diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index ca08eca4a4..4ab8553298 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -308,9 +308,19 @@ impl DocSetup { pub fn keep_in_range(&mut self) { self.bleed = bleed_in_range(self.bleed); for m in [&mut self.superscript, &mut self.subscript] { + // `clamp` passes NaN through, so a non-finite value falls back to the default first. + if !m.size.is_finite() { + m.size = ScriptMetrics::DEFAULT.size; + } + if !m.position.is_finite() { + m.position = ScriptMetrics::DEFAULT.position; + } m.size = m.size.clamp(1.0, MAX_SCRIPT); m.position = m.position.clamp(-MAX_SCRIPT, MAX_SCRIPT); } + if !self.small_caps_size.is_finite() { + self.small_caps_size = DocSetup::default().small_caps_size; + } self.small_caps_size = self.small_caps_size.clamp(1.0, MAX_SMALL_CAPS); } } @@ -353,6 +363,20 @@ mod tests { assert!(s.has_bleed() && !DocSetup::default().has_bleed()); } + #[test] + fn keep_in_range_replaces_non_finite_type_values() { + let mut s = DocSetup::default(); + s.superscript.size = f64::NAN; + s.superscript.position = f64::INFINITY; + s.subscript.size = f64::NEG_INFINITY; + s.subscript.position = f64::NAN; + s.small_caps_size = f64::NAN; + s.keep_in_range(); + for v in [s.superscript.size, s.superscript.position, s.subscript.size, s.subscript.position, s.small_caps_size] { + assert!(v.is_finite(), "{v}"); + } + } + #[test] fn presets_and_defaults() { let d = DocSetup::default(); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a13fb21680..0b205a5b16 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -388,6 +388,18 @@ fn char_position_round_trips() { assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9); } +#[test] +fn optical_kerning_round_trips_and_old_style_defaults_to_auto() { + let st = CharStyle { optical_kerning: true, kerning: Some(120.0), ..CharStyle::default() }; + let value = serde_json::to_value(&st).unwrap(); + assert_eq!(value["opticalKerning"], true); + assert_eq!(serde_json::from_value::(value.clone()).unwrap(), st); + let mut old = value; + old.as_object_mut().unwrap().remove("opticalKerning"); + assert!(!serde_json::from_value::(old).unwrap().optical_kerning); + assert!(serde_json::to_value(CharStyle::default()).unwrap().get("opticalKerning").is_none()); +} + #[test] fn units() { assert_eq!(Unit::Inches.parse("1"), Some(72.0)); diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 0e3aea70e9..5189e7aa28 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -25,9 +25,12 @@ pub struct CharStyle { /// Tracking in 1/1000 em. #[serde(default)] pub tracking: f64, - /// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em. + /// Manual pair spacing in 1/1000 em; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option, + /// Use glyph shapes for automatic pair spacing; false uses font metrics. + #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] + pub optical_kerning: bool, #[serde(default)] pub baseline_shift: f64, #[serde(default = "hundred")] @@ -266,6 +269,7 @@ impl Default for CharStyle { leading: None, tracking: 0.0, kerning: None, + optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, v_scale: 100.0, diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 47106d7882..b66795e890 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -223,6 +223,7 @@ impl ParaList { position: CharPosition::Normal, tracking: 0.0, kerning: None, + optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, strikethrough: false, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f495697ceb..7b1199277b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,6 +36,7 @@ vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } image = { workspace = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } flate2 = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). roxmltree = "0.21" diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc047d9d65..8758262628 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -87,6 +87,7 @@ pub mod swatchlib; pub mod symbollib; pub(crate) mod tabs; mod textedit; +pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; @@ -182,20 +183,22 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) } } -/// A document is open and it is not in isolation mode: Object › Lock's and Object › Hide's items, -/// Unlock All and Show All are off in isolation mode. Pattern editing mode and opacity mask -/// editing isolate their art too, and do not count as isolation mode here while their own layer -/// is the isolated one. An object isolated inside them counts. -pub fn outside_isolation(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let editing_layer = |l| st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == l) || st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == l); - if st.isolation.is_some_and(|l| !editing_layer(l)) { Err("exit isolation mode first".into()) } else { Ok(()) } +/// The isolated group, layer or object in isolation mode. Pattern editing mode and opacity mask +/// editing isolate their own layer, which does not count here; an object isolated inside them +/// counts. +pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { + st.isolation.filter(|l| !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)) } -/// Objects are selected ([`has_selection`]) and the document is not in isolation mode -/// ([`outside_isolation`]). -pub fn has_selection_outside_isolation(s: &Session) -> std::result::Result<(), String> { - outside_isolation(s)?; - has_selection(s) +/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at +/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. +pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; + if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } +} +/// Whether `id` lies inside the isolated object `root` (the root itself does not). +pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { + id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) } pub fn can_undo(s: &Session) -> std::result::Result<(), String> { s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 8ef171d326..3b9a476d42 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -125,7 +125,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used", + "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do strokes in the art of a brush that is used", has_doc, brush_unused ), @@ -134,7 +134,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art). scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 66dd546e90..9cc52c82c8 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -362,14 +362,15 @@ fn art_brushes(n: &Node, out: &mut Vec) { } /// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph -/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush -/// that a counted stroke paints with. +/// designs, pattern tiles and the tiles that pattern editing's Cancel puts back, and graphic styles +/// count, and so do the strokes in the art of every brush that a counted stroke paints with. pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result { let d = &s.doc()?.doc; let lib = brush::library(d); let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); - trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + trees.chain(patterns.flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo)); let mut used = BTreeSet::new(); while let Some(name) = todo.pop() { @@ -389,7 +390,77 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); if let Some(params) = p.get("params") { + let original = v.clone(); merge(&mut v, params); + if lib[i].kind.type_id() == "pattern" { + let tiles = [ + ("side_tile", "side"), + ("outer_corner_tile", "outer_corner"), + ("inner_corner_tile", "inner_corner"), + ("start_tile", "start"), + ("end_tile", "end"), + ]; + // Resolve all Original choices against the brush before any tile can clear the art + // another corner borrows. Keep the matching frame with each copied tile. + let originals: Vec<_> = tiles + .iter() + .map(|(_, art)| { + let from = if art.ends_with("corner") + && original.get(art).is_none_or(Value::is_null) + && original.get(if *art == "outer_corner" { "outer_source" } else { "inner_source" }).is_none_or(Value::is_null) + { + if *art == "outer_corner" { "inner_corner" } else { "outer_corner" } + } else { + *art + }; + (original.get(from).cloned().unwrap_or(Value::Null), original.get(format!("{from}_frame")).cloned().unwrap_or(Value::Null)) + }) + .collect(); + for ((tile, art), (original_art, original_frame)) in tiles.into_iter().zip(originals) { + let frame = format!("{art}_frame"); + let swatch = format!("{art}_swatch"); + let Some(choice) = params.get(tile) else { + if params.get(art).is_some() { + if params.get(frame.as_str()).is_none() { + v[frame.as_str()] = Value::Null; + } + if params.get(swatch.as_str()).is_none() { + v[swatch.as_str()] = Value::Null; + } + } + continue; + }; + let (choice, swatch_only) = if let Some(name) = choice.as_object() { + (name.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(C, "invalid pattern tile choice"))?, true) + } else { + (choice.as_str().ok_or_else(|| bad(C, "invalid pattern tile choice"))?, false) + }; + if art == "side" && choice == "none" && !swatch_only { + return Err(bad(C, "You must choose a side pattern.")); + } + if choice == "original" && !swatch_only { + v[art] = original_art; + v[frame.as_str()] = original_frame; + v[swatch.as_str()] = Value::Null; + } else if !swatch_only && (choice == "none" || (art.ends_with("corner") && brush::CornerSource::parse(choice).is_some())) { + v[art] = Value::Null; + v[frame.as_str()] = Value::Null; + v[swatch.as_str()] = Value::Null; + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else { + let pattern = s.doc()?.doc.pattern(choice).ok_or_else(|| bad(C, format!("no pattern named `{choice}`")))?; + let copy = Node::new(NodeId(0), NodeKind::Group { children: pattern.art.clone(), clip: false }); + v[art] = serde_json::to_value(copy).unwrap_or_default(); + v[frame.as_str()] = serde_json::to_value(pattern.tile).unwrap_or_default(); + v[swatch.as_str()] = json!(choice); + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } } let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); if let Some(nn) = &new_name { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a2cab84a89..3534d40ac5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -566,17 +566,29 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { /// rest still go to the compound path, which holds the paint. pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), true)) + Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true)) +} + +/// [`selected_roots`] for the selected objects inside the isolated object `root` +/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the +/// objects held by another selected object are dropped. A selected path of a compound path stands +/// for its compound unless the compound is `root` or `members` is set (as in +/// [`selected_roots_to_transform`]). +pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { + let st = s.doc()?; + let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); + Ok(roots_within(&st.doc, ids, |compound| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their /// compound, and ids whose ancestor is also listed, and layers, are dropped. pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { - roots_within(doc, ids, false) + roots_within(doc, ids, |_| false) } -/// [`roots_of`]; with `members`, a compound path's member listed stays itself. -fn roots_within(doc: &Document, ids: Vec, members: bool) -> Vec { +/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the +/// compound's id. +fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); // A compound-path member acts as its compound (compounds are one object). @@ -586,7 +598,7 @@ fn roots_within(doc: &Document, ids: Vec, members: bool) -> Vec let path = paths.get(&id); let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty()); match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) { - Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members => (n.id, Some(up.to_vec())), + Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())), _ => (id, path.cloned()), } }) diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 5ad8054fae..4745437d40 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -447,25 +447,206 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// Expand the pattern fills under `root` that paint a transparent or colorized image into the tiles they paint /// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other /// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through -/// pixels), when it has a colorize paint, or when it, a group +/// pixels), when it has a colorize paint that `colorize` counts, or when it, a group /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending -/// mode. Returns how many shapes changed. -pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet) -> Result { - let (_, n) = replace_leaves(d, root, |d, l| { - // Most leaves have no pattern fill: skip the ancestry walk for them. - if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { - return None; +/// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded +/// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden +/// groups or layers and in template layers stay as they are. A pattern fill in tile art counts +/// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is +/// expanded again for it. A pattern fill stays, and a live object stays live, when its art would +/// take the expanded art past [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. +/// Returns how many objects changed. +pub(crate) fn expand_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result { + expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED) +} + +/// [`expand_transparent_image_patterns`] with the expanded art held to `budget` objects. +pub(crate) fn expand_transparent_image_patterns_within( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + budget: usize, +) -> Result { + let mut changed = 0; + let made = std::cell::Cell::new(0usize); + // Each pass brings the patterns in the expanded tiles' art up one level. + for levels in (1..=PATTERN_LEVELS).rev() { + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels, &made, budget)?; + let (_, n) = replace_leaves(d, root, |d, l| { + // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. + if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + return None; + } + // The expanded art would be shown. + if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { + return None; + } + let which = |d: &Document, i: &AppearanceItem| transparent_pattern_fill(d, l, i, see_through, colorize, levels); + let art = expand_patterns_where(d, l, which, budget - made.get())?; + // The copies of the shape's other items count too. + let count = art.count_with_masks(); + if count > budget - made.get() { + return None; + } + made.set(made.get() + count); + Some(art) + })?; + if live + n == 0 { + break; } - let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); - let transparent = |d: &Document, i: &AppearanceItem| { - pattern_fill(d, i).is_some_and(|(f, def, _)| { - let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(a, see_through, on)) - }) - }; - expand_patterns_where(d, l, transparent) - })?; - Ok(n) + changed += live + n; + } + Ok(changed) +} + +/// How many levels of patterns the canvas draws: a pattern fill in the art of a pattern, and so +/// on, as [`vectorcraft_render`] draws them. +const PATTERN_LEVELS: u32 = 3; + +/// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would +/// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]). +pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { + d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize, PATTERN_LEVELS)) +} + +/// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends, +/// envelopes, repeats and Intertwine groups) with a pattern fill that +/// [`transparent_pattern_fill`] counts with `levels`. Guides, clipping paths and template layers +/// don't count. +fn holds_transparent_image_patterns( + d: &Document, + n: &Node, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, +) -> bool { + if !drawn(n) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize, levels)) + } + _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize, levels))), + } +} + +/// Whether `n` is shown and isn't a template layer. +fn drawn(n: &Node) -> bool { + n.visible && !matches!(n.kind, NodeKind::Layer { template: true, .. }) +} + +/// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a +/// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for +/// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for +/// everything nested in each), so the shapes they draw are leaves. The objects that art holds count +/// in `made`, and an object whose art would take `made` past `budget` stays live. Returns how many +/// were expanded. +fn expand_live_with_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, + made: &std::cell::Cell, + budget: usize, +) -> Result { + fn outermost( + d: &Document, + n: &Node, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, + out: &mut Vec, + ) { + if !drawn(n) { + return; + } + match &n.kind { + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + if holds_transparent_image_patterns(d, n, see_through, colorize, levels) { + out.push(n.id); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + children.iter().for_each(|c| outermost(d, c, see_through, colorize, levels, out)); + } + _ => {} + } + } + /// Fresh ids for everything under `n`: copies of the same art share theirs. + fn fresh_ids(d: &mut Document, n: &mut Node) { + for c in n.children_mut().into_iter().flatten() { + let c = Arc::make_mut(c); + c.id = d.alloc_id(); + fresh_ids(d, c); + } + } + let mut live = vec![]; + if let Some(n) = d.node(root) { + outermost(d, n, see_through, colorize, levels, &mut live); + } + let mut count = 0; + for id in &live { + if made.get() >= budget { + break; + } + let Some(n) = d.node(*id) else { continue }; + // Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]), + // and leave the object live when that can't be done. + let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue }; + // An object whose art would take the expanded art past the budget stays live. + let size = g.count_with_masks(); + if size > budget - made.get() { + continue; + } + made.set(made.get() + size); + g.id = *id; + fresh_ids(d, &mut g); + *d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g; + count += 1; + } + Ok(count) +} + +/// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image +/// ([`transparent_image`], through pattern fills in that art down to `levels` patterns), +/// counting the fill's and the shape's opacity and blending mode. +fn transparent_pattern_fill( + d: &Document, + l: &Node, + i: &AppearanceItem, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, +) -> bool { + let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); + pattern_fill_holds_transparent_image(d, i, see_through, colorize, shape, levels) +} + +/// Whether `i` is a pattern fill whose tile art holds a transparent image ([`transparent_image`]), +/// down to `levels` patterns, counting the fill's opacity and blending mode, or anything when `on`. +fn pattern_fill_holds_transparent_image( + d: &Document, + i: &AppearanceItem, + keys: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + on: bool, + levels: u32, +) -> bool { + if levels == 0 { + return false; + } + let Some((f, def, _)) = pattern_fill(d, i) else { return false }; + let on = on || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(d, a, keys, colorize, on, levels - 1)) } /// Whether `n` has opacity or a blending mode of its own. @@ -473,13 +654,21 @@ fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal } -/// Whether `n` is or holds an image with see-through pixels (key in `keys`), a colorize paint, -/// opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`. -fn transparent_image(n: &Node, keys: &BTreeSet, on: bool) -> bool { +/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a +/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in +/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down +/// to `levels` patterns. Hidden art doesn't count. +fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool { + if !n.visible { + return false; + } let on = on || blended(n); match &n.kind { - NodeKind::Image(im) => on || keys.contains(&im.key) || n.extras().colorize.is_some(), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))), + NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels)) + } + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on, levels))), } } @@ -491,12 +680,12 @@ fn transparent_image(n: &Node, keys: &BTreeSet, on: bool) -> bool { /// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill /// lays a tile. fn expand_patterns(d: &mut Document, l: &Node) -> Option { - expand_patterns_where(d, l, |_, _| true) + expand_patterns_where(d, l, |_, _| true, usize::MAX) } /// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other -/// items. -fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option { +/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects. +fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option { if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i)) { @@ -509,19 +698,47 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & let mut parts = vec![]; let mut rest = vec![]; let mut expanded = false; + // What `assemble` adds around the tiles when every picked fill expands: a copy of the path for + // each run of other items, a group around the parts and one for the path's transparency, and + // the path's opacity mask. + let (mut copies, mut run, mut picked) = (0usize, false, vec![]); + for i in &l.appearance.items { + if let Some((f, _, _)) = pattern_fill(d, i).filter(|_| which(d, i)) { + run = false; + picked.push(f.opacity < 1.0 || f.blend != BlendMode::Normal); + } else if i.visible() && !i.paint().is_none() && !run { + (copies, run) = (copies + 1, true); + } + } + let group = copies + picked.len() > 1 || !l.appearance.effects.is_empty(); + // A lone tile group with transparency of its own goes in a group for the path's. + let transparency = blended(l) && !group && picked.first().is_some_and(|b| *b); + let around = copies.saturating_mul(l.count()) + usize::from(group) + usize::from(transparency) + l.count_with_masks().saturating_sub(l.count()); + let mut left = budget.saturating_sub(around); + // A fill that expands while others follow leaves room for the copy and group that those take + // if they don't fit, and once one doesn't fit, the ones after it stay too. + let (mut later, mut full) = (picked.len(), false); for item in &l.appearance.items { let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf)); - let tiles = fill.and_then(|(f, def, xf)| { + later -= usize::from(fill.is_some()); + let room = if later > 0 { left.saturating_sub(l.count() + 1) } else { left }; + let tiles = fill.filter(|_| !full).and_then(|(f, def, xf)| { let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?; - let t = pattern_tiles(d, &def, xf, bounds); + let Some(t) = pattern_tiles(d, &def, xf, bounds, room) else { + full = true; + return None; + }; (!t.is_empty()).then_some((f, fl, t)) }); - let Some(art) = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)) else { + let art = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)); + full |= art.as_ref().is_some_and(|a| a.count_with_masks() > room); + let Some(art) = art.filter(|a| a.count_with_masks() <= room) else { if item.visible() && !item.paint().is_none() { rest.push(item.clone()); } continue; }; + left -= art.count_with_masks(); if !rest.is_empty() { parts.push(styled_copy(d, l, std::mem::take(&mut rest))); } @@ -548,30 +765,38 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & /// not, and when it does more than move art that holds a symbol instance, whose strokes the canvas /// draws scaled with the tile and an instance does not scale. Random Transform effects and brushes /// that vary at random in the art are baked first ([`seeds_baked`], [`random_brushes_baked`]). -fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect) -> Vec { +/// `None` when the tiles would hold more than `budget` objects. +fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, budget: usize) -> Option> { if !moves_only(xf) && def.art.iter().any(|a| has_instances(a)) { - return vec![]; + return Some(vec![]); } let Some(def) = seeds_baked(def) else { - return vec![]; + return Some(vec![]); }; let brushes = vectorcraft_brush::library(d); let def = random_brushes_baked(d, &brushes, def); let def = &*def; + let per_tile = def.art.iter().map(|a| a.count_with_masks()).sum::(); + if def.offsets_covering(xf.inverse().transform_rect_bbox(bounds)).len().saturating_mul(per_tile) > budget { + return None; + } let scaling = Scaling { strokes: true, effects: Some(vectorcraft_render::effects::scale_effect), patterns: true, ..Scaling::default() }; if scales_evenly(xf) && (moves_only(xf) || !def.art.iter().any(|a| has_geometry_effects(a))) { - return def.instances_in_with(xf, bounds, scaling); + return Some(def.instances_in_with(xf, bounds, scaling)); } if def.art.iter().any(|a| has_unbakeable_effects(a)) { - return vec![]; + return Some(vec![]); } let placed = Scaling { patterns: true, ..Scaling::default() }; let mut tiles = def.instances_in_with(Affine::IDENTITY, xf.inverse().transform_rect_bbox(bounds), placed); + // Outlined strokes and effects can make more objects than the art had. + let mut left = budget; for t in &mut tiles { *t = prepared(d, &brushes, t); + left = left.checked_sub(t.count_with_masks())?; place_art(t, xf, scaling); } - tiles + Some(tiles) } /// Pattern `def` with each path in its art (opacity masks included) that has a random Transform diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index c8cb7218a7..7471ffb56a 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -33,6 +33,7 @@ pub(crate) mod imagemap; mod legacy_ai; mod load; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; +mod jp2read; mod metafile; mod naming; mod native; @@ -193,6 +194,8 @@ mod tests_psd; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_jp2read; #[cfg(test)] mod tests_pcxread; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index d1db603025..e11b6adcd6 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -34,6 +34,7 @@ struct Run<'a> { override_export: bool, destination: &'a str, dest_folder: Option<&'a str>, + dataset_file_naming: &'a str, } /// Play `commands` on each source file or data set. @@ -90,6 +91,7 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { override_export: bool_or(p, "overrideExport", true), destination, dest_folder: dest_folder.as_deref(), + dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")), }; match source { "folder" => batch_folder(s, C, p, override_open, &run), @@ -135,9 +137,6 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: #[cfg(not(target_arch = "wasm32"))] fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { - use super::distinct_names; - use super::screens::file_part; - let st = s.doc()?; let names: Vec = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); if names.is_empty() { @@ -147,11 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - // Data set files are named File + Data Set Name (helpx, for Override Save/Export; the folder - // destination uses the same name). `file_part` writes the characters Windows does not allow in a - // file name (`/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters) in the data set's - // name as `-`, and `distinct_names` adds `-2`, `-3`… to a name an earlier data set used. - let stems = distinct_names(names.iter().map(|name| format!("{doc_stem}_{}", file_part(name)))); + let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -227,7 +222,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou "folder" => { let folder = run.dest_folder.ok_or_else(|| bad("action.batch", "missing destination folder"))?; let out_ext = if ext.is_empty() { "vectorcraft" } else { ext }; - let out = std::path::Path::new(folder).join(format!("{stem}.{out_ext}")); + let out = output_path(folder, stem, out_ext).ok_or_else(|| bad("action.batch", "unsafe destination file name"))?; let out = out.to_string_lossy().into_owned(); // When `close` is false (data sets), write a copy so the template keeps its path. write_result(s, &out, out_ext, !close)?; @@ -240,6 +235,174 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou } } +/// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3` +/// suffixes when a stem was used earlier or its output already exists in a folder the batch may +/// read and write. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Result> { + use super::screens::{file_part, safe_file_name}; + + if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { + return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`")); + } + let doc_stem = safe_file_name(doc_stem); + let doc_stem = if doc_stem.is_empty() || matches!(doc_stem.as_str(), "." | "..") { "Untitled" } else { &doc_stem }; + let bases = names.iter().enumerate().map(|(i, name)| { + let safe = file_part(name); + let safe_data_set = safe_file_name(&safe); + let ordinal = format!("{doc_stem}{:03}", i + 1); + match naming { + "fileNumber" => ordinal, + "dataSetName" if !safe_data_set.is_empty() => safe_data_set, + "dataSetName" => ordinal, + _ => format!("{doc_stem}_{safe}"), + } + }); + let outputs = dataset_output_extensions(run, doc); + let mut taken = std::collections::HashSet::new(); + let mut reserved = std::collections::HashSet::new(); + let mut stems = Vec::with_capacity(bases.len()); + for base in bases { + let mut candidate = base.clone(); + let mut suffix = 2; + while taken.contains(&candidate.to_lowercase()) + || dataset_output_paths(run.dest_folder, &candidate, &outputs, doc) + .iter() + .any(|path| reserved.contains(&path.to_string_lossy().to_lowercase())) + || dataset_output_exists(run.dest_folder, &candidate, &outputs, doc) + { + if suffix > 10_000 { + return Err(bad("action.batch", "no free data set file name in destination folder")); + } + candidate = format!("{base}-{suffix}"); + suffix += 1; + } + taken.insert(candidate.to_lowercase()); + reserved + .extend(dataset_output_paths(run.dest_folder, &candidate, &outputs, doc).into_iter().map(|path| path.to_string_lossy().to_lowercase())); + stems.push(candidate); + } + Ok(stems) +} + +#[cfg(not(target_arch = "wasm32"))] +struct DatasetOutput { + ext: String, + artboards: bool, + joiner: &'static str, +} + +/// Lists step output extensions and reserves artboard file names for saves with any artboard or +/// exports with multiple artboards. Per-artboard names count for vectorcraft, template, AI and AIT +/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec { + let mut outputs = Vec::new(); + if run.destination == "folder" { + outputs.push(DatasetOutput { ext: "vectorcraft".into(), artboards: false, joiner: "-" }); + } + for step in run.steps { + let id = step.get("command").and_then(Value::as_str).unwrap_or(""); + let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + || (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection")); + if writes { + let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); + let ext = match format { + Some(format) if super::format(format).is_some() => format_extension(format), + Some(_) => continue, + None => "vectorcraft".to_string(), + }; + if safe_extension(&ext) { + let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft"); + let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let artboards = if is_save { + !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") + } else { + doc.artboards.len() > 1 + && id == "document.export" + && matches!( + format_id, + "svg" + | "svgz" + | "eps" + | "png" + | "jpg" + | "webp" + | "gif" + | "png8" + | "tiff" + | "bmp" + | "tga" + | "psd" + | "dxf" + | "emf" + | "wmf" + | "ai" + ) + }; + outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } }); + } + } + } + outputs +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_exists(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> bool { + let Some(folder) = folder else { return false }; + if super::may_read(folder).is_err() || super::may_write(folder).is_err() { + return false; + } + dataset_output_paths(Some(folder), stem, outputs, doc).iter().any(|path| { + let path_text = path.to_string_lossy(); + super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_paths(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> Vec { + let Some(folder) = folder else { return Vec::new() }; + let boards: Vec<_> = (0..doc.artboards.len()).collect(); + let mut parts = super::artboard_file_names(doc, &boards); + for board in boards { + parts.extend(super::artboard_file_names(doc, &[board])); + } + let mut paths = Vec::new(); + for output in outputs { + if !safe_extension(&output.ext) || super::format(&output.ext).is_none() { + continue; + } + paths.extend(output_path(folder, stem, &output.ext)); + if output.artboards { + for part in &parts { + paths.extend(output_path(folder, &format!("{stem}{}{part}", output.joiner), &output.ext)); + } + } + } + paths +} + +/// Returns whether an extension is safe to use in an output file name. +#[cfg(not(target_arch = "wasm32"))] +fn safe_extension(ext: &str) -> bool { + !ext.is_empty() && !ext.contains(['/', '\\', ':']) && !ext.contains("..") +} + +/// Returns a path inside the destination folder for a safe stem and extension. +#[cfg(not(target_arch = "wasm32"))] +fn output_path(folder: &str, stem: &str, ext: &str) -> Option { + use std::path::Path; + if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(std::path::is_separator) || !safe_extension(ext) { + return None; + } + let name = format!("{stem}.{ext}"); + if name.contains(std::path::is_separator) { + return None; + } + let path = Path::new(folder).join(name); + (path.parent() == Some(Path::new(folder))).then_some(path) +} + /// Save when the extension is a Save format; otherwise export (PNG, JPEG…). /// `as_copy`: `file.saveCopy` so the open document keeps its path (data-set batches). #[cfg(not(target_arch = "wasm32"))] @@ -285,7 +448,10 @@ fn rewrite_paths( Some(f) => format_extension(f), None => default_ext.to_string(), }; - let file = std::path::Path::new(folder).join(format!("{stem}.{ext}")); + if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) { + return c; + } + let Some(file) = output_path(folder, stem, &ext) else { return c }; params.insert("path".into(), json!(file.to_string_lossy())); if let Some(o) = c.as_object_mut() { o.insert("params".into(), Value::Object(params)); @@ -411,6 +577,74 @@ mod tests { assert!(dest.join("b.svg").is_file(), "b.svg written"); } + #[cfg(unix)] + #[test] + fn batch_folder_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-src"); + let dest = tmp("backslash-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "object.unlockAll", "params": {}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert!(dest.join("a\\b.svg").is_file(), "{r}"); + } + + #[cfg(unix)] + #[test] + fn batch_folder_override_export_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-export-src"); + let dest = tmp("backslash-export-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert_eq!(file_names(&dest), ["a\\b.svg"], "{r}"); + } + + #[test] + fn output_path_accepts_only_platform_file_name_separators() { + let folder = tmp("output-path"); + let folder = folder.to_string_lossy(); + let backslash = output_path(&folder, "a\\b", "svg"); + #[cfg(windows)] + assert!(backslash.is_none()); + #[cfg(not(windows))] + assert_eq!(backslash, Some(std::path::Path::new(folder.as_ref()).join("a\\b.svg"))); + for stem in ["a/b", ".", "..", ""] { + assert!(output_path(&folder, stem, "svg").is_none(), "{stem:?}"); + } + #[cfg(windows)] + assert_eq!(std::path::Path::new("a\\b.svg").file_stem(), Some(std::ffi::OsStr::new("b"))); + } + #[test] fn batch_skips_open_steps_when_override_open() { let src = tmp("open"); @@ -548,6 +782,412 @@ mod tests { s } + fn named_batch(s: &mut Session, dest: &std::path::Path, naming: Option<&str>) -> Value { + let mut p = json!({ + "source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "object.unlockAll", "params": {}}] + }); + if let Some(naming) = naming { + p["datasetFileNaming"] = json!(naming); + } + s.execute("action.batch", &p).unwrap() + } + + #[test] + fn batch_data_set_naming_choices_and_omitted_default() { + for (i, (naming, want)) in [ + (Some("fileNumber"), ["source001.vectorcraft", "source002.vectorcraft"]), + (Some("fileDataSetName"), ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + (Some("dataSetName"), ["Alpha.vectorcraft", "Beta.vectorcraft"]), + (None, ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + ] + .into_iter() + .enumerate() + { + let dest = tmp(&format!("choice-{i}")); + let mut s = with_data_sets(&["Alpha", "Beta"]); + let saved = tmp(&format!("saved-{i}")).join("source.vectorcraft"); + s.execute("document.save", &json!({"path": saved.to_string_lossy()})).unwrap(); + let r = named_batch(&mut s, &dest, naming); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), want, "{naming:?}: {r}"); + } + } + + #[test] + fn batch_file_number_uses_three_digits_through_500() { + let names: Vec = (1..=500).map(|n| format!("Set {n}")).collect(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + dataset_file_naming: "fileDataSetName", + }; + let stems = dataset_stems(&names, "source", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(); + for n in [1, 2, 10, 100, 500] { + assert_eq!(stems[n - 1], format!("source{n:03}")); + } + } + + #[test] + fn batch_unsaved_data_set_names_and_empty_fallback() { + let dest = tmp("unsaved-number"); + let mut s = with_data_sets(&["Alpha"]); + assert_eq!(named_batch(&mut s, &dest, Some("fileNumber"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled001.vectorcraft"]); + let dest = tmp("unsaved-name"); + assert_eq!(named_batch(&mut s, &dest, Some("fileDataSetName"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled_Alpha.vectorcraft"]); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + dataset_file_naming: "fileDataSetName", + }; + assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); + } + + #[test] + fn batch_data_set_name_collisions_and_existing_files() { + let clear = tmp("choice-collision-clear"); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &clear, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&clear), ["a-b-2.vectorcraft", "a-b.vectorcraft"]); + let dest = tmp("choice-collision"); + std::fs::write(dest.join("a-b.vectorcraft"), b"keep").unwrap(); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("a-b.vectorcraft")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["a-b-2.vectorcraft", "a-b-3.vectorcraft", "a-b.vectorcraft"]); + } + + #[test] + fn batch_data_set_name_avoids_windows_device_files() { + let dest = tmp("choice-device"); + let mut s = with_data_sets(&["CON"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), ["CON-.vectorcraft"]); + } + + #[test] + fn batch_override_export_keeps_existing_output() { + let dest = tmp("choice-existing-export"); + std::fs::write(dest.join("Alpha.svg"), b"keep").unwrap(); + let mut s = with_data_sets(&["Alpha"]); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("Alpha.svg")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); + } + + #[test] + fn batch_artboard_export_keeps_existing_output() { + let dest = tmp("choice-existing-artboard-export"); + let existing = dest.join("Alpha-Artboard-1.png"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "png", "useArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.png", "Alpha-2-Artboard-2.png", "Alpha-Artboard-1.png"]); + } + + #[test] + fn batch_remembered_separate_artboards_keeps_existing_output() { + let source = tmp("choice-remembered-separate-source"); + let dest = tmp("choice-remembered-separate-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": source.join("source.vectorcraft").to_string_lossy(), "separateArtboards": true})).unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save"}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!( + file_names(&dest), + ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2-Artboard-2.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft",] + ); + } + + #[test] + fn batch_single_artboard_save_keeps_existing_artboard_file() { + let source = tmp("choice-single-artboard-source"); + let dest = tmp("choice-single-artboard-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 1})).unwrap(); + s.execute( + "document.save", + &json!({ + "path": source.join("source.vectorcraft").to_string_lossy(), + "separateArtboards": true + }), + ) + .unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft"]); + } + + #[test] + fn batch_pdf_export_ignores_artboard_named_file() { + let dest = tmp("choice-pdf-artboard-name"); + let existing = dest.join("Alpha-Artboard-1.pdf"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "pdf"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.pdf", "Alpha.pdf"]); + } + + #[test] + fn batch_separate_artboards_ignores_unrelated_extension() { + let dest = tmp("choice-separate-unrelated-extension"); + let unrelated = dest.join("Alpha-photo.png"); + std::fs::write(&unrelated, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(unrelated).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.vectorcraft", "Alpha-Artboard-2.vectorcraft", "Alpha-photo.png", "Alpha.vectorcraft"]); + } + + #[test] + fn batch_separate_artboards_reserves_prior_output_names() { + let dest = tmp("choice-separate-reserved"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha-Artboard-1"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert!(dest.join("Alpha-Artboard-1.vectorcraft").exists()); + assert!(dest.join("Alpha-Artboard-1-2.vectorcraft").exists()); + } + + #[test] + fn batch_does_not_probe_a_denied_destination() { + let allowed = tmp("probe-allowed"); + let denied = tmp("probe-denied"); + std::fs::write(denied.join("Alpha.svg"), b"private").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[allowed.as_path()], &[allowed.as_path()]).unwrap().unwrap(); + let steps = [json!({"command": "document.export", "params": {"format": "svg"}})]; + let folder = denied.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", + }; + crate::file_access::confine(Some(&roots), || { + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Alpha"] + ); + let mut s = with_data_sets(&["Alpha"]); + let result = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", "destination": "none", + "destinationFolder": folder, "overrideExport": true, + "commands": steps, + }), + ) + .unwrap(); + assert!(!result.to_string().contains("Alpha-2"), "{result}"); + }); + } + + #[test] + fn batch_does_not_probe_unknown_format_paths() { + let root = tmp("probe-format"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside"), b"private").unwrap(); + for format in ["../outside", "x/../../outside", "..\\..\\outside"] { + let steps = [json!({"command": "document.export", "params": {"format": format}})]; + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", + }; + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)) + .unwrap_or_else(|e| panic!("{format}: {e}")), + ["Alpha"], + "{format}" + ); + assert_eq!(rewrite_paths(&steps, false, true, Some(&folder), "Alpha", "vectorcraft"), steps, "{format}"); + } + } + + #[test] + fn batch_probe_and_dot_names_stay_in_destination() { + let root = tmp("probe-parent"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", + }; + assert_eq!( + dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001", "Untitled002"] + ); + assert_eq!( + dataset_stems(&["Alpha".into()], "..", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001"] + ); + let output = root.join("named"); + let mut s = with_data_sets(&[".", ".."]); + let r = named_batch(&mut s, &output, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&output), ["Untitled001.vectorcraft", "Untitled002.vectorcraft"]); + } + + #[test] + fn batch_probe_rejects_parent_escape() { + let root = tmp("probe-parent-only"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + assert!(!dataset_output_exists( + Some(&folder), + "../outside", + &[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-" }], + &vectorcraft_doc::Document::new(100.0, 80.0), + )); + } + + #[test] + fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() { + let mut s = with_data_sets(&["Alpha"]); + let e = s + .execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})) + .unwrap_err(); + let msg = e.to_string(); + for value in ["fileNumber", "fileDataSetName", "dataSetName"] { + assert!(msg.contains(value), "{msg}"); + } + assert!( + s.execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": 7, "commands": [{"command": "object.unlockAll"}]})).is_err() + ); + let src = tmp("folder-ignore-src"); + write_svg(&src, "one.svg", "#f00"); + let r = s.execute("action.batch", &json!({"source": "folder", "folder": src.to_string_lossy(), "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + } + #[test] fn batch_keeps_data_set_files_inside_the_destination_folder() { let root = tmp("set-names-root"); diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index abd6857adc..9c6861f555 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document (source: datasets; File + Data Set Name for the folder destination and Override Save/Export, with `/`, `\\`, `:`, `<`, `>`, `\"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and `-2`, `-3`… added to a name already used). Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index a05cc08248..49ecfaa345 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; -use super::super::flatten::{FlattenOptions, flatten_document}; +use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -152,6 +152,8 @@ fn parse(p: &Value) -> Result { let overprint = choice("overprints", q.overprints.clone(), Overprint::from_id, d.overprint, "preserve or discard")?; let mut flatten = flattener(&q, &[])?; flatten.preserve_overprints &= overprint == Overprint::Preserve; + // The writer draws colorized images in their ink. + flatten.keeps_colorize = true; let level = q.level.as_ref().map(super::dxf::text); let eps = EpsOptions { level: choice("level", level, Level::from_id, d.level, "2 or 3")?, @@ -299,11 +301,13 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result { return Err(bad(C, "the document has no artboard")); } let regions: Vec = pages.iter().map(|(_, region, _)| *region).collect(); - let transparent = doc.layers.iter().any(|l| l.shows_transparency()); - let flat = flatten_document(doc, &set.flatten)?; - let drawn = flat.as_ref().unwrap_or(doc); + let expanded = expand_transparent_tile_images(doc, &set.flatten)?; + let source = expanded.as_ref().unwrap_or(doc); + let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l)); + let flat = flatten_expanded(source, &set.flatten)?; + let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; - if transparent && flat.is_some() { + if transparent && (flat.is_some() || expanded.is_some()) { enc.warnings.push("transparency is flattened into opaque art and images (EPS has none): see the flattener preset".into()); } let preview_limit = if saving { SAVE_PREVIEW } else { MAX_PREVIEW }; diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f727215341..a1687e214f 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -491,6 +491,8 @@ pub const FORMATS: &[Format] = &[ reader("ps", "PostScript", &["ps"], "application/postscript", false), // ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them. reader("pcx", "PCX", &["pcx"], "image/x-pcx", true), + // JP2 and raw codestreams are decoded to PNG; JPX composition is not supported. + reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true), ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). @@ -515,6 +517,12 @@ pub const OPEN_EXTS: &[&str] = &[ "icb", "vst", "pcx", + "jpf", + "jpx", + "jp2", + "j2k", + "j2c", + "jpc", "psd", "psb", "vctemplate", @@ -531,10 +539,10 @@ pub const OPEN_EXTS: &[&str] = &[ /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa or PCX type (File › Open and Place still read them all). On Linux the +/// `.epsf`, `.ps`, Targa, PCX or JPEG 2000 type (File › Open and Place still read them all). On Linux the /// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer /// VectorCraft for it. -pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx"]; +pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares /// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order. @@ -581,6 +589,12 @@ pub const PLACE_EXTS: &[&str] = &[ "icb", "vst", "pcx", + "jpf", + "jpx", + "jp2", + "j2k", + "j2c", + "jpc", "psd", "psb", "vctemplate", diff --git a/crates/engine/src/cmd/fileio/jp2read.rs b/crates/engine/src/cmd/fileio/jp2read.rs new file mode 100644 index 0000000000..9e0752c2c5 --- /dev/null +++ b/crates/engine/src/cmd/fileio/jp2read.rs @@ -0,0 +1,279 @@ +//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is +//! bounded before allocation and converted to RGBA for the common PNG storage path. + +use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image}; +use vectorcraft_color::cms::{IccProfile, Intent}; + +/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest. +pub(super) fn is_jpeg2000(bytes: &[u8]) -> bool { + bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || bytes.starts_with(b"\xff\x4f") +} + +/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level. +pub(super) fn boxes(b: &[u8]) -> impl Iterator { + let mut at = 0usize; + std::iter::from_fn(move || { + let header = b.get(at..at.checked_add(8)?)?; + let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?); + let (length, head) = match size { + 0 => (b.len().checked_sub(at)?, 8usize), + 1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize), + n => (n as usize, 8usize), + }; + if length < head { + return None; + } + let end = at.checked_add(length)?; + let data = b.get(at.checked_add(head)?..end)?; + let ty = header.get(4..8)?; + at = end; + Some((ty, data)) + }) +} + +/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c. +fn unsupported_jpx_content(bytes: &[u8]) -> bool { + fn association_has_content(data: &[u8], depth: usize) -> bool { + if depth >= 16 { + return true; + } + boxes(data).any(|(ty, child)| { + matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) + }) + } + let mut codestreams = 0u8; + for (ty, data) in boxes(bytes) { + match ty { + b"jp2c" => { + codestreams = codestreams.saturating_add(1); + if codestreams > 1 { + return true; + } + } + b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, + b"asoc" if association_has_content(data, 0) => return true, + _ => {} + } + } + false +} + +/// The largest embedded ICC profile read. +const MAX_PROFILE: usize = 4 * 1024 * 1024; +/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2). +const MAX_TILES: u64 = 65_535; +/// Bytes the decoder keeps for each component of each tile before decoding any of them. +const TILE_COMPONENT_BYTES: u64 = 256; + +/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component +/// count, the image size and the tile count. +fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { + let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; + if stream.get(..4)? != b"\xff\x4f\xff\x51" { + return None; + } + let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; + let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; + if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { + return None; + } + let be32 = |range: std::ops::Range| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); + let width = be32(8..12)?.checked_sub(be32(16..20)?)?; + let height = be32(12..16)?.checked_sub(be32(20..24)?)?; + // Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles. + let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { + (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), + _ => None, + }; + let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; + let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; + Some((count as u64, width, height, across.checked_mul(down)?)) +} + +/// One `jp2h` header with at most one palette, component mapping and channel definition box, so +/// the checks below read the boxes the decoder uses. +fn single_header_boxes(bytes: &[u8]) -> bool { + let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); + let (Some((_, header)), None) = (headers.next(), headers.next()) else { + return false; + }; + [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) +} + +/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels +/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read; +/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives +/// `Some(0)`, which no image matches. +fn channel_definitions(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\xff\x4f") { + return None; + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; + let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; + let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); + let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { + return Some(0); + }; + // (channel, type, association) by channel. + let mut defs: Vec<[u16; 3]> = + entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); + defs.sort_unstable(); + let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); + let colors = defs.len() - usize::from(opacity); + let mut seen = vec![false; colors]; + let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { + usize::from(channel) == i + && (i >= colors + || (kind == 0 + && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) + }); + Some(if layout_ok { defs.len() as u64 } else { 0 }) +} + +/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`) +/// beside it needs one entry per column, each naming a codestream component and, when it maps +/// through the palette, a palette column; anything else is `Err`. +fn palette_columns(bytes: &[u8], components: u64) -> Result, ()> { + if bytes.starts_with(b"\xff\x4f") { + return Ok(None); + } + let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { + return Ok(None); + }; + let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { + return Ok(None); + }; + let columns = palette.get(2).copied().ok_or(())?; + // Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are. + let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; + if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { + return Err(()); + } + // Without a mapping the decoder maps every column from the first component. + let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { + return Ok(Some(u64::from(columns))); + }; + if mapping.len() != usize::from(columns) * 4 { + return Err(()); + } + for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { + let valid = u64::from(u16::from_be_bytes([c0, c1])) < components + && match kind { + 0 => true, + 1 => column < columns, + _ => false, + }; + if !valid { + return Err(()); + } + } + Ok(Some(u64::from(columns))) +} + +/// Decode within the raster allocation allowance, counting source samples, RGBA output, and +/// decoder intermediates. The decoder may need multiple full-sized component planes. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) { + return Err("the JPEG 2000 file can't be read".into()); + } + let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?; + if tile_count == 0 || tile_count > MAX_TILES { + return Err("the JPEG 2000 file can't be read".into()); + } + let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); + if declared_w == 0 + || declared_h == 0 + || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) + || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + // The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file. + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); + if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?; + // The decoder keeps each palette value in 8 bytes and each row in its own list. + let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); + if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) + && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let (w, h) = (image.width(), image.height()); + let color = image.color_space(); + let channels = match color { + ColorSpace::Gray => 1, + ColorSpace::RGB => 3, + ColorSpace::CMYK => 4, + ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(), + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let stride = u64::from(channels) + u64::from(image.has_alpha()); + // The decoder sizes its output by the palette's columns and writes one channel per mapping + // entry, so the columns, the entries and the output channels must all match. + if palette.is_some_and(|columns| columns != stride) { + return Err("the JPEG 2000 file can't be read".into()); + } + // The decoder reorders the channels by their definitions (`cdef`) and drops any channel without + // one, so a definition is needed for every channel it writes. + if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { + return Err("the JPEG 2000 file can't be read".into()); + } + let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); + let too_large = || format!("an image of {w} × {h} pixels is too large to draw"); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?; + let size = pixels.checked_mul(stride).ok_or_else(too_large)?; + let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?; + // hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second + // f32 coefficient plane per component. Palette mapping or channel definitions + // can temporarily clone the component planes. Reserve another 8 bytes per + // pixel for IDWT and code-block scratch while samples and RGBA coexist. + let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?; + let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?; + let working = + size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?; + if w == 0 || h == 0 || working > max_alloc { + return Err(too_large()); + } + let len = usize::try_from(size).map_err(|_| too_large())?; + let mut samples = vec![0; len]; + image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let profile = match color { + ColorSpace::Icc { profile, .. } => { + Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?) + } + _ => None, + }; + let cms = vectorcraft_color::cms::active(); + let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?); + for sample in samples.chunks_exact(stride as usize) { + let at = |i: usize| sample.get(i).copied().unwrap_or(0); + let rgb = match (color, profile.as_ref()) { + (ColorSpace::Gray, _) => [at(0); 3], + (ColorSpace::RGB, _) => [at(0), at(1), at(2)], + (ColorSpace::CMYK, _) => { + cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + (ColorSpace::Icc { .. }, Some(profile)) => { + let mut values = [0.0f32; 4]; + for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) { + *dst = f32::from(*src) / 255.0; + } + profile + .to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric) + .ok_or("the JPEG 2000 file has an unsupported color space or JPX content")? + .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let [r, g, b] = rgb; + rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]); + } + image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into()) +} diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 0e53a5a18f..7cbbda2fed 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -167,7 +167,7 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> { let keys = super::super::flatten::see_through_images(d); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); for id in layers { - super::super::expand::expand_transparent_image_patterns(d, id, &keys)?; + super::super::expand::expand_transparent_image_patterns(d, id, &keys, &|_, _| true)?; } Ok(()) } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index a281d471a8..0667ad9e9d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -97,6 +97,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if psdread::is_psd(bytes) { return format(if psdread::is_psb(bytes) { "psb" } else { "psd" }); } + if super::jp2read::is_jpeg2000(bytes) { + return format("jpeg2000"); + } if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { return Some(f); } @@ -629,6 +632,9 @@ pub fn raster_image(bytes: &[u8]) -> Result { let cms = vectorcraft_color::cms::active(); return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi); } + if super::jp2read::is_jpeg2000(bytes) { + return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?; if reader.format().is_none() && super::tgaread::is_targa(bytes) { reader.set_format(image::ImageFormat::Tga); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 4394773c6e..6826d318e8 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -328,9 +328,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3, /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` -/// options over it; images with see-through pixels and colorized images count as transparency, -/// rasterized areas are clipped to their regions, and discarded overprints are dropped. `None` -/// when nothing changes (or the file keeps transparency). +/// options over it; images with see-through pixels and colorized images, including those in +/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and +/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency). fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result> { if !set.pdf13() { return Ok(None); diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 61b7417567..fd2ffbf8c2 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -1,6 +1,6 @@ //! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and //! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX -//! header's HDpi and VDpi. Place +//! header's HDpi and VDpi, or JP2 capture and display resolution boxes. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it //! as a `pHYs` chunk. @@ -24,12 +24,47 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { super::psdread::resolution(bytes) } else if super::pcxread::is_pcx(bytes) { super::pcxread::resolution(bytes) + } else if super::jp2read::is_jpeg2000(bytes) { + jp2(bytes) } else { None }; r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) } +fn jp2_axis(n: u16, d: u16, e: i8) -> Option { + if d == 0 { + return None; + } + let ppi = f64::from(n) / f64::from(d) * 10f64.powi(i32::from(e)) * INCH_M; + (ppi.is_finite() && (1.0..=100_000.0).contains(&ppi)).then_some(ppi) +} + +/// JP2 resolution is independent on each axis. Later capture or display boxes replace earlier +/// valid values for that axis; an invalid later axis leaves the earlier value intact. +fn jp2(b: &[u8]) -> Option<(f64, f64)> { + if !b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") { + return Some((72.0, 72.0)); + } + let (mut x, mut y) = (None, None); + for (_, header) in super::jp2read::boxes(b).filter(|(ty, _)| *ty == b"jp2h") { + for (_, res) in super::jp2read::boxes(header).filter(|(ty, _)| *ty == b"res ") { + for (_, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") { + let Some([vn0, vn1, vd0, vd1, hn0, hn1, hd0, hd1, ve, he]): Option<[u8; 10]> = data.get(..10).and_then(|v| v.try_into().ok()) else { + continue; + }; + if let Some(value) = jp2_axis(u16::from_be_bytes([hn0, hn1]), u16::from_be_bytes([hd0, hd1]), he as i8) { + x = Some(value); + } + if let Some(value) = jp2_axis(u16::from_be_bytes([vn0, vn1]), u16::from_be_bytes([vd0, vd1]), ve as i8) { + y = Some(value); + } + } + } + } + Some((x.unwrap_or(72.0), y.unwrap_or(72.0))) +} + /// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { b.get(at..at.checked_add(n)?) diff --git a/crates/engine/src/cmd/fileio/tests_jp2read.rs b/crates/engine/src/cmd/fileio/tests_jp2read.rs new file mode 100644 index 0000000000..54481c4038 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_jp2read.rs @@ -0,0 +1,293 @@ +//! JPEG 2000 Open, Place, pixel and resolution regressions using original synthetic fixtures. + +use serde_json::json; + +use super::jp2read::is_jpeg2000; +use super::*; + +const JP2: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker.jp2"); +const RAW: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-raw.j2k"); +const PPI300: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-300ppi.jp2"); +const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]]; + +fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> { + let raster = load::raster_image(bytes).unwrap(); + image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec { + let mut out = ((data.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend(ty); + out.extend(data); + out +} + +fn with_resolution(children: &[Vec]) -> Vec { + let mut file = JP2.to_vec(); + let at = file.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + let old_len = u32::from_be_bytes(file[at..at + 4].try_into().unwrap()) as usize; + let mut header = file[at + 8..at + old_len].to_vec(); + if !children.is_empty() { + header.extend(boxed(b"res ", &children.concat())); + } + file.splice(at..at + old_len, boxed(b"jp2h", &header)); + file +} + +fn res(ty: &[u8; 4], vr: u16, hr: u16) -> Vec { + let mut data = Vec::new(); + for n in [vr, hr] { + data.extend(n.to_be_bytes()); + data.extend(254u16.to_be_bytes()); + } + data.extend([2, 2]); + boxed(ty, &data) +} + +#[test] +fn checker_opens_and_places_with_exact_pixels() { + for (name, bytes) in [("checker.jp2", JP2), ("checker-raw.j2k", RAW)] { + assert_eq!(pixels(bytes), COLORS, "{name}"); + let mut s = Session::new(); + let encoded = vectorcraft_format::base64_encode(bytes); + let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(opened["format"], "jpeg2000"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0)); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(placed["format"], "jpeg2000"); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + assert!(load::texture_image(bytes).is_ok()); + } +} + +#[test] +fn signatures_and_every_extension() { + assert!(is_jpeg2000(JP2) && is_jpeg2000(RAW)); + for ext in ["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"] { + assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("jpeg2000")); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext)); + } + assert_eq!(load::detect("unknown.bin", JP2).map(|f| f.id), Some("jpeg2000")); + assert_eq!(load::detect("unknown.bin", RAW).map(|f| f.id), Some("jpeg2000")); +} + +#[test] +fn resolution_boxes_use_last_valid_axis_and_72_fallback() { + let check = |children: &[Vec], want: (f64, f64)| { + let file = with_resolution(children); + let got = ppi::resolution(&file).unwrap(); + assert!((got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01, "{got:?} != {want:?}"); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 144.0 / want.0).abs() < 0.01 && (size.height - 144.0 / want.1).abs() < 0.01); + }; + check(&[], (72.0, 72.0)); + check(&[res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resc", 30000, 30000), res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resc", 30000, 15000)], (150.0, 300.0)); + assert_eq!(ppi::resolution(RAW), Some((72.0, 72.0))); + assert!((ppi::resolution(PPI300).unwrap().0 - 300.0).abs() < 0.01); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 0.48).abs() < 0.001 && (size.height - 0.48).abs() < 0.001); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + let stored = ppi::resolution(&blob.bytes).unwrap(); + assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01); +} + +#[test] +fn malformed_resolution_and_image_data_are_bounded() { + let good = res(b"resc", 30000, 15000); + let mut zero = res(b"resd", 15000, 15000); + zero[10..12].copy_from_slice(&0u16.to_be_bytes()); + let got = ppi::resolution(&with_resolution(&[good.clone(), zero])).unwrap(); + assert!((got.0 - 150.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01); + let short = boxed(b"resd", &[0; 9]); + assert!(ppi::resolution(&with_resolution(&[good.clone(), short])).unwrap().0 > 149.0); + assert_eq!(ppi::resolution(&with_resolution(&[boxed(b"resc", &[0; 9])])), Some((72.0, 72.0))); + let mut over = good.clone(); + over[..4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&with_resolution(&[over])), Some((72.0, 72.0))); + let mut outer_over = JP2.to_vec(); + let jp2h = outer_over.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + outer_over[jp2h..jp2h + 4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&outer_over), Some((72.0, 72.0))); + let mut extended = Vec::from(1u32.to_be_bytes()); + extended.extend(b"resd"); + extended.extend(26u64.to_be_bytes()); + extended.extend(&res(b"resd", 15000, 30000)[8..]); + assert!(ppi::resolution(&with_resolution(&[extended])).unwrap().0 > 299.0); + let mut to_end = res(b"resd", 15000, 30000); + to_end[..4].copy_from_slice(&0u32.to_be_bytes()); + assert!(ppi::resolution(&with_resolution(&[to_end])).unwrap().0 > 299.0); + for bytes in [&JP2[..12], &RAW[..4], &JP2[..JP2.len() - 5]] { + assert!(load::raster_image(bytes).is_err()); + } + assert!(super::jp2read::decode(JP2, 8).is_err()); + // RGBA (16 bytes) and the float component planes (48 bytes) each fit; + // their concurrent allocation with samples and scratch does not. + assert!(super::jp2read::decode(JP2, 80).unwrap_err().contains("too large to draw")); + let mut huge = RAW.to_vec(); + huge[8..12].copy_from_slice(&100_000u32.to_be_bytes()); + huge[12..16].copy_from_slice(&100_000u32.to_be_bytes()); + assert!(load::raster_image(&huge).is_err()); + let mut jpx = JP2.to_vec(); + jpx.extend(boxed(b"jp2c", RAW)); + assert!(load::raster_image(&jpx).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut layered = JP2.to_vec(); + layered.extend(boxed(b"jpch", &[])); + assert!(load::raster_image(&layered).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut wrapped = JP2.to_vec(); + wrapped.extend(boxed(b"asoc", &boxed(b"jp2c", RAW))); + assert!(load::raster_image(&wrapped).err().unwrap().to_string().contains("unsupported color space or JPX content")); +} + +#[test] +fn compatible_jpx_brand_alone_keeps_checker_pixels() { + let mut branded = JP2.to_vec(); + branded[12..16].copy_from_slice(&24u32.to_be_bytes()); + branded.splice(32..32, b"jpx ".iter().copied()); + assert_eq!(pixels(&branded), COLORS); +} + +#[test] +fn codestream_component_count_bounds_decode_planes() { + assert_eq!(super::jp2read::decode(RAW, 1000).unwrap().pixels().map(|p| p.0).collect::>(), COLORS); + let mut many = RAW.to_vec(); + let component = many[42..45].to_vec(); + many.splice(42..42, component.repeat(17)); + many[4..6].copy_from_slice(&98u16.to_be_bytes()); // 38 + 3 * 20 + many[40..42].copy_from_slice(&20u16.to_be_bytes()); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("too large to draw")); + many[0..4].copy_from_slice(&[0, 0, 0, 0]); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("can't be read")); +} + +fn with_header_boxes(extra: &[Vec]) -> Vec { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let mut children = header.to_vec(); + children.extend(extra.concat()); + super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat() +} + +#[test] +fn channel_definitions_must_cover_every_channel() { + // (channel, type, association): color channels 1 to 3, an opacity channel (type 1). + let cdef = |defs: &[[u16; 3]]| { + let mut data = (defs.len() as u16).to_be_bytes().to_vec(); + data.extend(defs.iter().flatten().flat_map(|v| v.to_be_bytes())); + boxed(b"cdef", &data) + }; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]])])), COLORS); + // Channel 0 as green and channel 1 as red swap the two. + let swapped = [[0, 255, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255], [255; 4]]; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 2], [1, 0, 1], [2, 0, 3]])])), swapped); + for defs in [ + vec![[0, 0, 1]], + vec![[0, 0, 1], [1, 0, 2], [2, 1, 0]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 3], [3, 1, 0]], + // Opacity first, a premultiplied opacity, a repeated color, an unassociated color. + vec![[0, 1, 0], [1, 0, 1], [2, 0, 2]], + vec![[0, 0, 1], [1, 0, 2], [2, 2, 0]], + vec![[0, 0, 1], [1, 0, 1], [2, 0, 3]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 0]], + ] { + assert!(load::raster_image(&with_header_boxes(&[cdef(&defs)])).err().unwrap().to_string().contains("can't be read"), "{defs:?}"); + } + // A second definition box, and a second header, are refused. + let full = cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]]); + assert!(load::raster_image(&with_header_boxes(&[full.clone(), cdef(&[[0, 0, 1]])])).err().unwrap().to_string().contains("can't be read")); + let mut two_headers = JP2.to_vec(); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + two_headers.extend(boxed(b"jp2h", header)); + assert!(load::raster_image(&two_headers).err().unwrap().to_string().contains("can't be read")); +} + +#[test] +fn palette_needs_one_mapping_per_column() { + // 256 entries of three 8-bit columns, entry i being (i, i, i). + let mut palette = vec![1, 0, 3, 7, 7, 7]; + palette.extend((0..=255u8).flat_map(|i| [i; 3])); + let pclr = boxed(b"pclr", &palette); + let mut deep = vec![1, 0, 3, 7, 7, 31]; + deep.extend((0..=255u8).flat_map(|i| [i, i, 0, 0, 0, i])); + let deep = boxed(b"pclr", &deep); + let cmap = |entries: &[[u8; 4]]| boxed(b"cmap", &entries.concat()); + // Each component through its own column gives the same pixels. + let mapped = with_header_boxes(&[pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 0, 0]])]); + assert_eq!(pixels(&mapped), COLORS); + // 256 rows of three 8-byte values and a 24-byte list each (12,288 bytes) pass a 12,000-byte allowance. + assert!(super::jp2read::decode(&mapped, 12_000).unwrap_err().contains("too large to draw")); + for extra in [ + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2], [0, 0, 1, 0]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 9, 1, 2]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 3]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1]])], + // A 32-bit column. + vec![deep.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2]])], + ] { + assert!(load::raster_image(&with_header_boxes(&extra)).err().unwrap().to_string().contains("can't be read")); + } +} + +#[test] +fn tile_grid_is_bounded_before_decoding() { + let tiled = |size: u32, tile: u32| { + let mut file = RAW.to_vec(); + file[8..12].copy_from_slice(&size.to_be_bytes()); + file[12..16].copy_from_slice(&size.to_be_bytes()); + file[24..28].copy_from_slice(&tile.to_be_bytes()); + file[28..32].copy_from_slice(&tile.to_be_bytes()); + file + }; + // 1,000 × 1,000 one-pixel tiles are more than a codestream can number. + assert!(super::jp2read::decode(&tiled(1000, 1), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + assert!(super::jp2read::decode(&tiled(2, 0), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + // 255 × 255 one-pixel tiles of three components need more than this allowance before decoding. + assert!(super::jp2read::decode(&tiled(255, 1), 1 << 20).unwrap_err().contains("too large to draw")); +} + +#[test] +fn cielab_images_are_refused() { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + // Enumerated color space 14, CIELab, with its default range and offset. + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &[1, 0, 0, 0, 0, 0, 14]) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat(); + assert!(load::raster_image(&file).err().unwrap().to_string().contains("unsupported color space")); +} + +#[test] +fn embedded_srgb_profile_keeps_checker_pixels() { + let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap(); + let mut colr_data = vec![2, 0, 0]; + colr_data.extend_from_slice(&icc); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &colr_data) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat(); + assert_eq!(pixels(&file), COLORS); + // A profile past 4 MiB is refused before the decoder reads the file. + let mut big = vec![2, 0, 0]; + big.resize(3 + 4 * 1024 * 1024 + 1, 0); + assert!(super::jp2read::decode(&with_header_boxes(&[boxed(b"colr", &big)]), MAX_RASTER_ALLOC).unwrap_err().contains("unsupported color space")); +} diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index 47a190a430..ccbe9c0493 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -49,7 +49,7 @@ mod presets; mod report; pub(crate) use analysis::{outlined_text, see_through_images}; -pub(crate) use apply::flatten_document; +pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images}; pub use commands::specs; pub use options::FlattenOptions; pub use presets::{FlattenerPreset, PRESET_EXTS, PRESET_FORMAT}; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 884351dea6..d229f1bbb8 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -74,7 +74,7 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let mut sc = Scratch { brushes: vectorcraft_brush::library(&baked), doc: baked.clone() }; let plain: Vec = art.iter().map(|n| sc.plain(n)).collect(); let reaches: Vec> = plain.iter().map(reach).collect(); - let see_through: Vec = plain.iter().map(|n| n.shows_transparency() || o.draws_see_through_image(n)).collect(); + let see_through: Vec = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). @@ -292,12 +292,46 @@ pub(super) fn opaque(n: &mut Node) { } } +/// Whether `doc` has pattern fills whose image tiles need transparency flattening with `o` +/// ([`expand_transparent_tile_images`]). +pub(crate) fn has_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> bool { + let keys = o.no_transparency.clone().unwrap_or_default(); + let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); + !doc.patterns.is_empty() && crate::cmd::expand::has_transparent_image_patterns(doc, &keys, &colorize) +} + +/// Expand pattern fills whose image tiles need transparency flattening. +pub(crate) fn expand_transparent_tile_images(doc: &Document, o: &FlattenOptions) -> Result> { + if !has_transparent_tile_images(doc, o) { + return Ok(None); + } + let keys = o.no_transparency.clone().unwrap_or_default(); + let colorize = |d: &Document, n: &Node| o.counts_colorize(d, n); + let mut d = doc.clone(); + let layers: Vec = + d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })).map(|l| l.id).collect(); + let mut changed = 0; + for id in layers { + changed += crate::cmd::expand::expand_transparent_image_patterns(&mut d, id, &keys, &colorize)?; + } + Ok((changed > 0).then_some(d)) +} + /// `doc` with everything it draws flattened with `o`, as formats without transparency (EPS) /// write it: every visible object of the visible layers, locked ones too (a clipping layer's -/// clipping path stays). `None` when that changes nothing. +/// clipping path stays). Pattern tile images with opacity, blending or a colorize paint that +/// `o` counts ([`FlattenOptions::counts_colorize`]) are expanded; see-through tile pixels are +/// expanded when `o.no_transparency` counts them. `None` when nothing changes. pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result> { + let expanded = expand_transparent_tile_images(doc, o)?; + Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded)) +} + +/// [`flatten_document`] for `doc` whose pattern tile images were expanded already +/// ([`expand_transparent_tile_images`]). +pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result> { let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints; - if !outlining && !doc.layers.iter().any(|l| l.shows_transparency() || o.draws_see_through_image(l)) { + if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) { return Ok(None); } let mut roots = vec![]; diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index 57331660ab..d4f18f3857 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -2,7 +2,7 @@ use super::analysis::draws_image; use super::apply::{apply, kept_work, plan}; use super::presets::{FlattenerPreset, saved_preset}; use super::report::target_roots; -use super::{BTreeSet, Deserialize, EngineError, Node, Result, Serialize, Session, Value, bad, json, str_param}; +use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param}; /// Object → Flatten Transparency settings: a preset's, adjusted by the command's params. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -34,6 +34,10 @@ pub struct FlattenOptions { /// amounts). `None` for ordinary flattening. Not a preset option. #[serde(skip)] pub no_transparency: Option>, + /// The file writes a colorized image in its colorize paint (EPS), so a colorize paint by + /// itself doesn't count as transparency. Not a preset option. + #[serde(skip)] + pub keeps_colorize: bool, } impl Default for FlattenOptions { @@ -81,6 +85,7 @@ impl FlattenOptions { preserve_alpha: false, preserve_overprints: true, no_transparency: None, + keeps_colorize: false, } } @@ -138,6 +143,21 @@ impl FlattenOptions { Ok(o) } + /// Whether `n`, art of `d`, shows transparency these options flatten + /// ([`Node::shows_transparency`], colorized images as [`Self::counts_colorize`] says). + pub(crate) fn shows_transparency(&self, d: &Document, n: &Node) -> bool { + n.shows_transparency_with(&|c| self.counts_colorize(d, c)) + } + + /// Whether colorized image `n`, art of `d`, counts as transparency by itself. With + /// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale + /// or 1-bit doesn't: the EPS writer draws it in that paint. + pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { + let NodeKind::Image(im) = &n.kind else { return true }; + let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })); + !self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none()) + } + /// `n` shows an image whose see-through pixels count as transparency. pub(super) fn draws_see_through_image(&self, n: &Node) -> bool { self.no_transparency.as_ref().is_some_and(|keys| draws_image(n, keys)) diff --git a/crates/engine/src/cmd/intertwine.rs b/crates/engine/src/cmd/intertwine.rs index 27f1080e1f..23f1be1906 100644 --- a/crates/engine/src/cmd/intertwine.rs +++ b/crates/engine/src/cmd/intertwine.rs @@ -3,18 +3,19 @@ //! `object.intertwine.make` puts the selected objects in an Intertwine group //! (`NodeKind::Intertwine`), `object.intertwine.release` gives them back as they were. In between, //! `object.intertwine.arrange` picks overlap areas, by a click (`at`) or by an enclosed path drawn -//! around them (`area`), and changes which member is drawn on top there: each member keeps the -//! area where it is drawn over the others (`NodeExtras::intertwine`, see -//! `vectorcraft_doc::intertwine`). Object › Expand turns the group into a plain group of what it -//! draws ([`expand_intertwines`]), which Ungroup takes apart. +//! around them (`area`), and changes the order the members are drawn in there: each member keeps +//! the areas where it is drawn over others, by tier (`NodeExtras::intertwine` and +//! `NodeExtras::intertwine_tiers`, see `vectorcraft_doc::intertwine`). Object › Expand turns the +//! group into a plain group of what it draws ([`expand_intertwines`]), which Ungroup takes apart. //! //! An overlap area is a face of the planar arrangement of what the members paint (their fills and //! strokes, type outlined; other objects by their bounds): the part where two or more of them //! overlap, split wherever a member's edge crosses it. //! //! Behaviour: (Make, -//! Release, clicking or drawing around an overlap, Bring to Front and Send to Back where three or -//! more objects overlap). +//! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward +//! and Send to Back where three or more objects overlap: +//! ). use std::sync::Arc; @@ -62,7 +63,7 @@ pub fn specs() -> Vec { "Arrange Intertwine Area", [], None, - "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|back (toggle: the object drawn right below the top comes to the front, so two objects swap), member?: id (front and back: the object to move; default: front brings the object right below the top, back sends the top one)} → {count: areas changed, top: [id of the object now on top in each area]}", + "{id?: Intertwine group (default: the selected one), at?: [x,y] (the overlap area under this point, as a click picks it) | area?: [[x,y]…] (a closed polygon drawn around overlap areas: every area whose inside it encloses), order?: toggle|front|forward|backward|back (toggle: the object drawn right below the top comes to the front, so two objects swap; forward and backward move an object one place up or down among the objects in that area; the others keep their order there), member?: id (front, forward, backward and back: the object to move; default: front and forward move the object right below the top, back and backward the top one)} → {count: areas changed (an area already in that order is not changed, and with none changed there is no undo step), top: [id of the object now on top in each changed area]}", has_doc, arrange ), @@ -173,7 +174,10 @@ fn release(s: &mut Session, _: &Value) -> Result { .flatten() .map(|c| { let mut c = (**c).clone(); - c.extras_mut().intertwine = None; + let mut e = c.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); + drop(e); c }) .collect(); @@ -228,6 +232,8 @@ pub(crate) fn expand_intertwines(d: &mut Document, roots: &[NodeId]) -> Result Option { Some(PathData::single(SubPath::polyline(&pts, true))) } -/// `n`'s area with `face` added (`add`) or taken out. -fn with_area(n: &mut Node, face: &PathData, add: bool) { - let old = n.extras().intertwine.as_deref().cloned(); - let new = match (old, add) { +/// Area `old` with `face` added (`add`) or taken out. +fn with_face(old: Option, face: &PathData, add: bool) -> Option { + match (old, add) { (None, true) => nonempty(face.clone()), (None, false) => None, (Some(a), true) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Union)), (Some(a), false) => nonempty(po::boolean(&a, FillRule::NonZero, face, FillRule::NonZero, po::BoolOp::Difference)), - }; - if new.as_ref() != n.extras().intertwine.as_deref() { - n.extras_mut().intertwine = new.map(Box::new); } } -/// Bring member `x` to the front of `face` (`front`) or send it to the back there; returns the -/// member now on top there. -fn arrange_face(children: &mut [Arc], face: &Face, x: usize, front: bool) -> Option { - let lowest = face.members.iter().min().copied()?; - let highest = face.members.iter().max().copied()?; - for &i in &face.members { - let Some(c) = children.get_mut(i) else { continue }; - let c = Arc::make_mut(c); - if front { - // Only `x` is drawn over the others here, unless it is on top in its own order. - with_area(c, &face.path, i == x && x != highest); - } else if i == x { - with_area(c, &face.path, false); - } else if x != lowest { - // Every other member is drawn over `x`, keeping their own order among them. - with_area(c, &face.path, true); +/// Draw `n` at `tier` in `face` (0: in its own order): `face` joins its area of that tier and +/// leaves its areas of the other tiers. +fn set_tier(n: &mut Node, face: &PathData, tier: usize) { + let e = n.extras(); + let mut areas: Vec> = + std::iter::once(e.intertwine.as_deref().cloned()).chain(e.intertwine_tiers.iter().map(|a| (!a.is_empty()).then(|| a.clone()))).collect(); + if areas.len() < tier { + areas.resize(tier, None); + } + for (k, a) in areas.iter_mut().enumerate() { + *a = with_face(a.take(), face, k + 1 == tier); + } + while areas.len() > 1 && areas.last().is_some_and(Option::is_none) { + areas.pop(); + } + let mut areas = areas.into_iter(); + let first = areas.next().flatten(); + let rest: Vec = areas.map(Option::unwrap_or_default).collect(); + if first.as_ref() != n.extras().intertwine.as_deref() || rest != n.extras().intertwine_tiers { + let mut e = n.extras_mut(); + e.intertwine = first.map(Box::new); + e.intertwine_tiers = rest; + } +} + +/// The tiers that draw members in `order` (bottom first): each member one tier above the member +/// below it when it comes before that member in the group's order, else at the same tier. +fn tiers(order: &[usize]) -> Vec<(usize, usize)> { + let mut tier = 0; + let mut below: Option = None; + order + .iter() + .map(|&i| { + if below.is_some_and(|b| i < b) { + tier += 1; + } + below = Some(i); + (i, tier) + }) + .collect() +} + +/// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they +/// are. +fn arrange_face(children: &mut [Arc], face: &Face, order: &[usize]) { + for (i, tier) in tiers(order) { + if let Some(c) = children.get_mut(i) { + set_tier(Arc::make_mut(c), &face.path, tier); } } - drawn_order(children, face).last().copied() +} + +/// `drawn` (the members of an area, bottom first) with member `x` moved as `order` says. +fn moved(drawn: &[usize], x: usize, order: Order) -> Vec { + let mut out = drawn.to_vec(); + let Some(at) = out.iter().position(|i| *i == x) else { return out }; + match order { + Order::Toggle | Order::Front => { + out.remove(at); + out.push(x); + } + Order::Back => { + out.remove(at); + out.insert(0, x); + } + Order::Forward if at + 1 < out.len() => out.swap(at, at + 1), + Order::Backward if at > 0 => out.swap(at - 1, at), + Order::Forward | Order::Backward => {} + } + out } fn arrange(s: &mut Session, p: &Value) -> Result { @@ -309,15 +362,17 @@ fn arrange(s: &mut Session, p: &Value) -> Result { let order = match str_param(p, "order").unwrap_or("toggle") { "toggle" => Order::Toggle, "front" => Order::Front, + "forward" => Order::Forward, + "backward" => Order::Backward, "back" => Order::Back, - o => return Err(bad(C, format!("unknown order `{o}`: toggle, front or back"))), + o => return Err(bad(C, format!("unknown order `{o}`: toggle, front, forward, backward or back"))), }; let member = match p.get("member") { Some(v) => Some(checked_id(s, v, C)?), None => None, }; if member.is_some() && order == Order::Toggle { - return Err(bad(C, "member is for order front or back")); + return Err(bad(C, "member is for order front, forward, backward or back")); } let children: Vec> = s.doc()?.doc.node(group).and_then(Node::children).cloned().unwrap_or_default(); let member = match member { @@ -345,25 +400,32 @@ fn arrange(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "that object is not in the overlap")); } - let tops = s.edit("Intertwine", |d, _| { + // The new order of each area that changes; areas already in that order are left out. + let mut plans: Vec<(&Face, Vec)> = vec![]; + for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) { + let drawn = drawn_order(&children, face); + let x = match (order, member) { + (_, Some(m)) => Some(m), + (Order::Toggle | Order::Front | Order::Forward, None) => drawn.iter().rev().nth(1).copied(), + (Order::Back | Order::Backward, None) => drawn.last().copied(), + }; + let Some(x) = x else { continue }; + let new = moved(&drawn, x, order); + if new != drawn { + plans.push((face, new)); + } + } + let tops: Vec = plans.iter().filter_map(|(_, new)| children.get(*new.last()?)).map(|c| c.id.0).collect(); + if plans.is_empty() { + return Ok(json!({ "count": 0, "top": tops })); + } + s.edit("Intertwine", |d, _| { let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?; let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) }; - let mut tops = vec![]; - for face in found.iter().filter(|f| member.is_none_or(|m| f.members.contains(&m))) { - let drawn = drawn_order(children, face); - let (x, front) = match (order, member) { - (Order::Toggle, _) => (drawn.iter().rev().nth(1).copied(), true), - (Order::Front, m) => (m.or(drawn.iter().rev().nth(1).copied()), true), - (Order::Back, m) => (m.or(drawn.last().copied()), false), - }; - let Some(x) = x else { continue }; - if let Some(top) = arrange_face(children, face, x, front) - && let Some(c) = children.get(top) - { - tops.push(c.id.0); - } + for (face, new) in &plans { + arrange_face(children, face, new); } - Ok(tops) + Ok(()) })?; - Ok(json!({ "count": tops.len(), "top": tops })) + Ok(json!({ "count": plans.len(), "top": tops })) } diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index aec4e32d00..5f438c8f5b 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -236,7 +236,7 @@ pub fn specs() -> Vec { "Create Gradient Mesh…", ["Object"], None, - "{ids?, rows?: n (4), cols?: n (4), appearance?: flat|center|edge, highlight?: % (100), at?: [x,y], columns?: as cols} convert filled paths into gradient meshes in their fill colour (a gradient fill: the colour it paints at each point), lightened per `appearance` (with `at`: 1×1 mesh plus lines through that point); an embedded image becomes a mesh over its rectangle (its transform kept) whose points take the average colour and opacity of the picture around them (a linked image is refused: embed it first) → {ids, index?}", + "{ids?, rows?: n (4), cols?: n (4), appearance?: flat|center|edge, highlight?: % (100), at?: [x,y], tolerance?: pt (0), columns?: as cols} convert filled paths into gradient meshes in their fill colour (a gradient fill: the colour it paints at each point), lightened per `appearance` (with `at`: 1×1 mesh plus lines through that point, or through the nearest point of the edge when `at` is outside within `tolerance`); an embedded image becomes a mesh over its rectangle (its transform kept) whose points take the average colour and opacity of the picture around them (a linked image is refused: embed it first) → {ids, index?}", has_selection, mesh_create ), @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "Add Mesh Line", [], None, - "{id, x, y, color?, keepModel?: bool (as paint.setFill)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope → {index}", + "{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", has_doc, mesh_add_line ), diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 602e2e3e96..bdba2b037a 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -16,8 +16,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { Some(a) => MeshAppearance::parse(a).ok_or_else(|| bad(C, "appearance must be flat|center|edge"))?, None => MeshAppearance::Flat, }; - check_numbers(p, &["highlight"], C)?; + check_numbers(p, &["highlight", "tolerance"], C)?; let highlight = f64_or(p, "highlight", 100.0).clamp(0.0, 100.0); + let tol = f64_or(p, "tolerance", 0.0).max(0.0); let at = match p.get("at") { None | Some(Value::Null) => None, Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?), @@ -58,7 +59,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { }; let Some(mut m) = m else { continue }; if let Some(q) = at { - index = m.add_lines_at(q); + index = m.add_lines_at(q, tol); } let mut mn = Node::new(n.id, NodeKind::Mesh(m)); mn.name = n.name.clone(); @@ -273,9 +274,11 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result { const C: &str = "object.mesh.addLine"; let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); crate::cmd::paint::check_keep_model(p, C)?; + check_numbers(p, &["tolerance"], C)?; + let tol = f64_or(p, "tolerance", 0.0).max(0.0); let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c)); let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| { - let i = m.add_lines_at(q).ok_or_else(|| bad(C, "point is outside the mesh"))?; + let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?; if let Some(c) = color { m.points[i].color = c; } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 7a93ac6176..73cf96c9ba 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selection, - has_selection_outside_isolation, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, + has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -43,8 +43,8 @@ pub fn specs() -> Vec { "All Artwork Above", ["Object", "Lock"], None, - "{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too) → {count}", - has_selection_outside_isolation, + "{} lock objects in the same layer that are above and overlap the selection, deselecting every selected object left locked or hidden (the key object too); in isolation mode, lock the selected objects and the objects above them inside the isolated object → {count}", + has_selected_member, |s, _| above(s, true) ), cmd!( @@ -52,8 +52,8 @@ pub fn specs() -> Vec { "Other Layers", ["Object", "Lock"], None, - "{} lock every layer that holds no selected object → {count}", - has_selection_outside_isolation, + "{} lock every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}", + has_selected_member, |s, _| other_layers(s, true) ), cmd!( @@ -61,8 +61,8 @@ pub fn specs() -> Vec { "Unselected Artwork", ["Object", "Lock"], Some("Cmd+Alt+Shift+2"), - "{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide → {count}", - has_selection, + "{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide, or inside the isolated object in isolation mode → {count}", + has_selected_member, |s, _| unselected_art(s, true) ), cmd!( @@ -70,8 +70,8 @@ pub fn specs() -> Vec { "All Artwork Above", ["Object", "Hide"], None, - "{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too) → {count}", - has_selection_outside_isolation, + "{} hide objects in the same layer that are above and overlap the selection, deselecting every selected object left hidden or locked (the key object too); in isolation mode, hide the selected objects and the objects above them inside the isolated object → {count}", + has_selected_member, |s, _| above(s, false) ), cmd!( @@ -79,8 +79,8 @@ pub fn specs() -> Vec { "Other Layers", ["Object", "Hide"], None, - "{} hide every layer that holds no selected object → {count}", - has_selection_outside_isolation, + "{} hide every layer that holds no selected object; in isolation mode, change nothing and return a count of 0 → {count}", + has_selected_member, |s, _| other_layers(s, false) ), cmd!( @@ -88,8 +88,8 @@ pub fn specs() -> Vec { "Unselected Artwork", ["Object", "Hide"], Some("Cmd+Alt+Shift+3"), - "{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; object.showAll shows them again; disabled in isolation mode → {count}", - has_selection_outside_isolation, + "{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; in isolation mode, only art inside the isolated object is affected; object.showAll shows them again → {count}", + has_selected_member, |s, _| unselected_art(s, false) ), cmd!( @@ -243,14 +243,21 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { // ---------- Lock / Hide ---------- fn above(s: &mut Session, lock: bool) -> Result { - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; + let st = s.doc()?; + let d = &st.doc; + let isolation = super::ordinary_isolation(st); + // In isolation mode a path of the isolated compound path is an object of its own. + let roots = match isolation { + Some(root) => super::edit::selected_roots_inside(s, root, false)?, + None => selected_roots(s)?, + }; let symbols = d.symbol_boxes(); - // `selected` holds each selected object's visual bounds, by layer, with the index there of its - // ancestor directly inside the layer. Symbol instances are measured by their art. + // `selected` holds each selected object's visual bounds, by layer (the isolated object in + // isolation mode), with the index there of its ancestor directly inside it. Symbol instances + // are measured by their art. let mut selected: BTreeMap> = BTreeMap::new(); for id in &roots { - let Some(layer) = d.layer_of(*id) else { continue }; + let Some(layer) = isolation.or_else(|| d.layer_of(*id)) else { continue }; // The selected object's ancestor directly inside the layer. let anc = d.ancestry(*id).unwrap_or_default(); let Some(pos) = anc.iter().position(|a| *a == layer) else { continue }; @@ -259,10 +266,14 @@ fn above(s: &mut Session, lock: bool) -> Result { let Some((_, idx, _)) = d.position(top) else { continue }; selected.entry(layer).or_default().push((idx, b)); } - // The loop walks up each layer once. Each object that is not selected and overlaps a selected - // object below it is locked (Lock) or hidden (Hide). + // The loop walks up each layer once, or the isolated object in isolation mode. Each object that + // is not selected and overlaps a selected object below it is locked (Lock) or hidden (Hide). In + // isolation mode the selected objects are locked or hidden too. let roots: HashSet = roots.into_iter().collect(); let mut hits: BTreeSet = BTreeSet::new(); + if isolation.is_some() { + hits.extend(roots.iter().copied()); + } for (layer, mut below) in selected { below.sort_by_key(|(idx, _)| *idx); let mut below = below.into_iter().peekable(); @@ -307,6 +318,11 @@ fn above(s: &mut Session, lock: bool) -> Result { fn other_layers(s: &mut Session, lock: bool) -> Result { let st = s.doc()?; + // In isolation mode the other layers lie outside the isolated group, layer or sublayer, so the + // document and its undo history stay as they are. + if super::ordinary_isolation(st).is_some() { + return Ok(json!({ "count": 0 })); + } let keep: Vec = st.selection.objects.iter().filter_map(|id| st.doc.ancestry(*id)).flatten().collect(); let others: Vec = st.doc.layers.iter().map(|l| l.id).filter(|l| !keep.contains(l)).collect(); let n = others.len(); @@ -370,10 +386,19 @@ fn unselected( } fn unselected_art(s: &mut Session, lock: bool) -> Result { - let roots = selected_roots_to_transform(s)?; + // In isolation mode the isolated object itself does not count as a selected object. + let iso = super::ordinary_isolation(s.doc()?); + let roots = match iso { + Some(root) => super::edit::selected_roots_inside(s, root, true)?, + None => selected_roots_to_transform(s)?, + }; let guides_locked = s.menu.guides_locked; let st = s.doc()?; - let ids = unselected(&st.doc, st.isolation, &st.selection.objects, &roots, guides_locked, lock); + let selection: Vec = match iso { + Some(root) => st.selection.objects.iter().copied().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(), + None => st.selection.objects.to_vec(), + }; + let ids = unselected(&st.doc, st.isolation, &selection, &roots, guides_locked, lock); // With nothing to lock (Lock) or hide (Hide), the document and its undo history stay as they are. if !ids.is_empty() { s.edit(if lock { "Lock" } else { "Hide" }, |d, _| { diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 325024bcb1..9cafae899a 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -129,7 +129,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result { { *clipping = false; } - c.opacity *= n.opacity; + // Each member keeps its own opacity; the group's opacity goes with the group. new_sel.push(c.id); out.push(c); } @@ -143,7 +143,7 @@ pub(super) fn ungroup(s: &mut Session, _: &Value) -> Result { } pub(super) fn lock(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_lock_hide_roots(s)?; // With every selected object already locked, the document and its undo history stay as they // are, and the objects are deselected. let d = &s.doc()?.doc; @@ -163,6 +163,16 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result { ok() } +/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in +/// isolation mode, only those inside the isolated object, where a path of the isolated compound +/// path is an object of its own. +fn selected_lock_hide_roots(s: &Session) -> Result> { + match crate::cmd::ordinary_isolation(s.doc()?) { + Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false), + None => selected_roots(s), + } +} + fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec { let mut v = vec![]; d.walk(|n| { @@ -174,14 +184,28 @@ fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec { } /// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole -/// document, or with `scope: "group"` inside the groups that hold the selected objects. A selected -/// group is the group that holds its own members, and the objects of a group inside another such -/// group are taken once. With `scope: "group"` and no selected object in a group, it returns an -/// error. +/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the +/// groups that hold the selected objects (in isolation mode, only the objects of those groups +/// that are inside the isolated object). A selected group is the group that holds its own +/// members, and the objects of a group inside another such group are taken once. With +/// `scope: "group"` and no selected object in a group, it returns an error. fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> bool) -> Result> { let st = s.doc()?; let d = &st.doc; if choice(p, cmd, "scope", &["document", "group"])? != Some("group") { + if let Some(root) = crate::cmd::ordinary_isolation(st) { + let mut ids = vec![]; + if let Some(node) = d.node(root) { + for child in node.children().into_iter().flatten() { + child.walk(&mut |n| { + if !n.is_layer() && f(n) { + ids.push(n.id); + } + }); + } + } + return Ok(ids); + } return Ok(collect_flag(d, f)); } let is_group = |id: &NodeId| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. })); @@ -204,6 +228,10 @@ fn collect_flag_in_scope(s: &Session, cmd: &str, p: &Value, f: impl Fn(&Node) -> }); } } + // In isolation mode only the objects inside the isolated object are taken. + if let Some(root) = crate::cmd::ordinary_isolation(st) { + v.retain(|id| crate::cmd::inside_isolation(d, root, *id)); + } Ok(v) } @@ -226,7 +254,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result { } pub(super) fn hide(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_lock_hide_roots(s)?; // With every selected object already hidden, the document and its undo history stay as they // are, and the objects are deselected. let d = &s.doc()?.doc; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d5885ad3cf..69f464edb1 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -6,7 +6,7 @@ use super::props::set_props; use super::shape::{expand_shape, set_live_shape}; use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again}; use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides}; -use crate::cmd::{has_selection_outside_isolation, outside_isolation}; +use crate::cmd::has_selected_member; pub fn specs() -> Vec { vec![ @@ -150,8 +150,8 @@ pub fn specs() -> Vec { "Selection", ["Object", "Lock"], Some("Cmd+2"), - "{ids?: [id…] (selected first; default: the selection)}", - has_selection_outside_isolation, + "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", + has_selected_member, lock ), cmd!( @@ -159,8 +159,8 @@ pub fn specs() -> Vec { "Unlock All", ["Object"], Some("Cmd+Alt+2"), - "{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", - outside_isolation, + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}", + has_doc, unlock_all ), cmd!( @@ -168,8 +168,8 @@ pub fn specs() -> Vec { "Selection", ["Object", "Hide"], Some("Cmd+3"), - "{ids?: [id…] (selected first; default: the selection)}", - has_selection_outside_isolation, + "{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}", + has_selected_member, hide ), cmd!( @@ -177,8 +177,8 @@ pub fn specs() -> Vec { "Show All", ["Object"], Some("Cmd+Alt+3"), - "{scope?: \"document\"|\"group\" (default document; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", - outside_isolation, + "{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}", + has_doc, show_all ), cmd!( diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 969daf4f6b..4c52da717e 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\" (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)", has_doc, set_format ), @@ -323,7 +323,13 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let kerning = match p.get("kerning") { None | Some(Value::Null) => None, Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(None), - Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number or \"auto\""))?.clamp(-1000.0, 10000.0))), + Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => None, + Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(C, "kerning must be a number, \"auto\", or \"optical\""))?.clamp(-1000.0, 10000.0))), + }; + let optical_kerning = match p.get("kerning") { + Some(Value::String(a)) if a.eq_ignore_ascii_case("auto") => Some(false), + Some(Value::String(a)) if a.eq_ignore_ascii_case("optical") => Some(true), + _ => None, }; let keys = [ "kerning", @@ -479,6 +485,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(k) = kerning { st.kerning = k; } + if let Some(v) = optical_kerning { + st.optical_kerning = v; + } if let Some(v) = baseline_shift { st.baseline_shift = v; } @@ -649,7 +658,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) + let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::>() }); + if let Some(kerning) = p.get("kerning") { + result["kerning"] = kerning.clone(); + } + Ok(result) } /// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame, diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 0face3aa8c..075bac2f5b 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -11,6 +11,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings}; use super::fileio::pdf::{merge, pdf_error}; use super::fileio::{extension, write_or_return}; +use super::flatten::has_transparent_tile_images; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; const SETUP: &str = "print.setup"; @@ -179,6 +180,12 @@ fn print(s: &mut Session, p: &Value) -> Result { // Raster effects print as images at the document's raster effects resolution. let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); + let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; + // The flattener expands pattern fills whose tile images need flattening, in the layers that print. + let tile_images = postscript + && !bitmap + && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? + .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -201,8 +208,7 @@ fn print(s: &mut Session, p: &Value) -> Result { None => Level::default(), }; let mut warnings = vec![]; - let bitmap = set.advanced.print_as_bitmap && set.output.mode == vectorcraft_pdf::OutputMode::Composite; - if !bitmap && doc.layers.iter().any(|l| l.shows_transparency()) { + if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { warnings.push("transparency is flattened into opaque art and images (PostScript has none): see flattenerPreset".to_string()); } if !set.color.profile.trim().is_empty() && set.output.mode == vectorcraft_pdf::OutputMode::Composite { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index cb4a51354a..8d393a58e9 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reset Tracking and Kerning", [], Some("Cmd+Alt+Q"), - "{ids?: [id…]} set tracking to 0 and kerning to Auto (the font's own kerning, which the Character panel shows as 0) in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", + "{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}", has_selection, reset_tracking ), @@ -300,6 +300,7 @@ pub(crate) struct CharChange { leading: Option>, tracking: Option, kerning: Option>, + optical_kerning: Option, baseline_shift: Option, h_scale: Option, v_scale: Option, @@ -476,7 +477,17 @@ impl CharChange { size: num("size"), leading: auto_or_num(p, "leading", cmd)?, tracking: num("tracking"), - kerning: auto_or_num(p, "kerning", cmd)?, + kerning: match p.get("kerning") { + None | Some(Value::Null) => None, + Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => None, + Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(None), + Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)), + }, + optical_kerning: match p.get("kerning") { + Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true), + Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false), + _ => None, + }, baseline_shift: num("baselineShift"), h_scale: num("hScale"), v_scale: num("vScale"), @@ -521,6 +532,7 @@ impl CharChange { && self.leading.is_none() && self.tracking.is_none() && self.kerning.is_none() + && self.optical_kerning.is_none() && self.baseline_shift.is_none() && self.h_scale.is_none() && self.v_scale.is_none() @@ -583,6 +595,9 @@ impl CharChange { if let Some(v) = self.kerning { st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0)); } + if let Some(v) = self.optical_kerning { + st.optical_kerning = v; + } if let Some(v) = self.baseline_shift { st.baseline_shift = v; } @@ -734,18 +749,53 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { if let Some(w) = super::fonts::set_font_warning(set) { out["warning"] = json!(w); } + if let Some(kerning) = p.get("kerning") { + out["kerning"] = kerning.clone(); + } Ok(out) } /// The em a laid-out glyph's kerning and tracking are measured in, in text space: the size it /// was shaped at (superscript, small caps and Shrink Text to Fit included). -fn glyph_em(t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option { - let face = vectorcraft_text::FontDb::global().face_by_id(g.font_id)?; +fn glyph_em(db: &vectorcraft_text::FontDb, t: &TextObject, g: &vectorcraft_text::PositionedGlyph) -> Option { + let face = db.face_by_id(g.font_id)?; let h_scale = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first()?.style.h_scale / 100.0; let [a, b, ..] = g.xf.as_coeffs(); Some(a.hypot(b) * face.units_per_em() / h_scale).filter(|em| em.is_finite() && *em > 0.0) } +/// The current pair correction in thousandths of an em, including an automatic correction. +pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &vectorcraft_text::TextLayout, x: usize, y: usize) -> f64 { + if let Some(value) = edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning) { + return value; + } + // Measure both layouts without wrapping so the same pair stays on one line. + let mut trial = t.clone(); + trial.kind = TextKind::Point; + let unwrapped = (!matches!(t.kind, TextKind::Point)).then(|| vectorcraft_text::layout(db, &trial)); + let original = unwrapped.as_ref().unwrap_or(lay); + edit::style_range(&mut trial.runs, x, y, |st| st.kerning = Some(0.0)); + let base = vectorcraft_text::layout(db, &trial); + let owner = original.glyphs.iter().find(|g| g.byte == x); + let rtl = owner.is_some_and(|g| g.rtl); + let drawn_gap = |layout: &vectorcraft_text::TextLayout| { + let first = layout.glyphs.iter().find(|g| g.byte == if rtl { y } else { x })?; + let following = layout.glyphs.iter().find(|g| g.byte == if rtl { x } else { y })?; + if first.line != following.line { + return None; + } + let axis = vectorcraft_geom::Vec2::new(first.angle.cos(), first.angle.sin()); + let along = if rtl { -axis } else { axis }; + let drawn = |g: &vectorcraft_text::PositionedGlyph| { + let [_, _, _, _, tx, ty] = g.xf.as_coeffs(); + Point::new(tx, ty) + }; + Some((drawn(following) - drawn(first)).dot(along)) + }; + let em = owner.and_then(|g| glyph_em(db, t, g)).unwrap_or(0.0); + if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 } +} + fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; @@ -780,18 +830,21 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { // A list marker's glyphs (length 0) stand for no character. let prev = lay.glyphs.iter().find(|h| h.line == g.line && h.len > 0 && h.byte + h.len == a); let pr = prev.map(|h| (h.byte, h.byte + h.len)); - let em = glyph_em(&t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; + let db = vectorcraft_text::FontDb::global(); + let em = glyph_em(db, &t, g).ok_or_else(|| bad(C, "the character's size can't be measured"))?; let em_prev = match prev { - Some(h) => Some(glyph_em(&t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?), + Some(h) => Some(glyph_em(db, &t, h).ok_or_else(|| bad(C, "the character's size can't be measured"))?), None if dx != 0.0 => return Err(bad(C, "the first character of a line has no character before it to kern: it moves only up and down (dy)")), None => None, }; - let kerning_in = |(x, y): (usize, usize)| edit::slice_runs(&t.runs, x, y).first().and_then(|r| r.style.kerning).unwrap_or(0.0); + let kerning_in = |(x, y): (usize, usize)| effective_kerning(db, &t, &lay, x, y); + let original_before = pr.map(kerning_in); + let original_own = kerning_in((a, b)); // The move along the line, in text space, limited to what kerning from -1000 to 10000 (1/1000 // em) on the character before it and on the character itself can give. let mut moved = dx / doc_len(along); - if let (Some(range), Some(ep)) = (pr, em_prev) { - let (kp, kc) = (kerning_in(range), kerning_in((a, b))); + if let (Some(_range), Some(ep)) = (pr, em_prev) { + let (kp, kc) = (original_before.unwrap_or(0.0), original_own); let hi = ((10000.0 - kp) * ep).min((kc + 1000.0) * em) / 1000.0; let lo = ((-1000.0 - kp) * ep).max((kc - 10000.0) * em) / 1000.0; if lo <= hi { @@ -803,7 +856,8 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { let touch = |t: &mut TextObject, before: Option, own: Option, raise: f64| { for (range, by) in [(pr, before), (Some((a, b)), own)] { if let (Some((x, y)), Some(by)) = (range, by) { - edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((st.kerning.unwrap_or(0.0) + by).clamp(-1000.0, 10000.0))); + let original = if (x, y) == (a, b) { original_own } else { original_before.unwrap_or(0.0) }; + edit::style_range(&mut t.runs, x, y, |st| st.kerning = Some((original + by).clamp(-1000.0, 10000.0))); } } edit::style_range(&mut t.runs, a, b, |st| { @@ -1086,9 +1140,20 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } _ => None, })?; + let mut caret_kerning = Vec::with_capacity(ranges.len()); + for &(id, a, b, caret) in &ranges { + let value = if matches!(step, Step::Kerning) && caret { + let t = text_ref(s, id)?; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b)) + } else { + None + }; + caret_kerning.push(value); + } if !ranges.is_empty() { s.edit("Character", |d, _| { - for &(id, a, b, _) in &ranges { + for (range_index, &(id, a, b, _)) in ranges.iter().enumerate() { let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?; let points = if matches!(step, Step::Size | Step::Leading | Step::BaselineShift) { t.style_scale().ok_or_else(|| bad(C, "text transform is collapsed or unrepresentable"))?.points @@ -1127,7 +1192,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result { st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?); } Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0), - Step::Kerning => st.kerning = Some((st.kerning.unwrap_or(0.0) + inc).clamp(-1000.0, 10000.0)), + Step::Kerning => { + let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0)); + st.kerning = Some((current + inc).clamp(-1000.0, 10000.0)); + } Step::BaselineShift => { st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?; } @@ -1142,9 +1210,10 @@ fn type_step(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ranges.iter().map(|(id, ..)| id.0).collect::>() })) } -/// Cmd/Ctrl+Alt+Q: tracking 0 and kerning Auto (0 in the Character panel) in the type objects in +/// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in /// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret, /// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there. +/// The automatic method remains selected. fn reset_tracking(s: &mut Session, p: &Value) -> Result { let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?; if !ranges.is_empty() { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 2a8d48fab5..30ccbfc7b7 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -8,7 +8,7 @@ use serde::Serialize; use serde::de::DeserializeOwned; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{CharStyle, Document, NodeId, NodeKind, ParaStyle, TextStyleDef}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef}; use super::typecmd::{refresh_bounds, text_targets}; use super::{CommandSpec, Result, Run, Session, bad, bool_or, has_doc, id_param, index, ok, str_param}; @@ -117,6 +117,14 @@ macro_rules! style_cmds { pub fn specs() -> Vec { let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character"); + v.push(spec( + "charStyle.edit", + "Edit Character Style", + &[], + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides", + |s, p| edit_style(s, p, Kind::Char), + true, + )); v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph")); v } @@ -152,6 +160,7 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("fontAxes", json!(v.font_axes)), ("leading", json!(v.leading)), ("kerning", json!(v.kerning)), + ("opticalKerning", json!(v.optical_kerning)), ("features", json!(v.features)), ("overprint_fill", json!(v.overprint_fill)), ("overprint_stroke", json!(v.overprint_stroke)), @@ -244,14 +253,16 @@ fn with_attrs(base: &T, attrs: &Map( cur: &T, attrs: fn(&T) -> Map, old: &Map, new: &Map, + base: &Map, ) -> T { let Some(full) = to_map(cur) else { return cur.clone() }; let mut m = attrs(cur); @@ -263,6 +274,14 @@ fn restyle( m.insert(k.clone(), v.clone()); } } + for (k, v) in old { + if !new.contains_key(k) + && m.get(k) == Some(v) + && let Some(base_value) = base.get(k) + { + m.insert(k.clone(), base_value.clone()); + } + } serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone()) } @@ -281,15 +300,47 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map st } -/// Every text object id in the document. -fn all_text(d: &Document) -> Vec { - let mut v = vec![]; - d.walk(|n| { - if matches!(n.kind, NodeKind::Text(_)) { - v.push(n.id) +/// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by +/// Cancel, and brush art, including opacity masks in those trees. +fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + fn has_text(n: &Node) -> bool { + matches!(n.kind, NodeKind::Text(_)) + || n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art)) + || n.children().is_some_and(|children| children.iter().any(|child| has_text(child))) + } + + fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + if let NodeKind::Text(t) = &mut n.kind { + f(t)?; } - }); - v + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && has_text(&mask.art) + { + visit(std::sync::Arc::make_mut(&mut mask.art), f)?; + } + for child in n.children_mut().into_iter().flatten() { + if has_text(child) { + visit(std::sync::Arc::make_mut(child), f)?; + } + } + Ok(()) + } + let trees = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)); + let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + for root in trees.chain(patterns.flat_map(|p| &mut p.art)) { + if has_text(root) { + visit(std::sync::Arc::make_mut(root), f)?; + } + } + let mut brushes = vectorcraft_brush::library(d); + let original_brushes = brushes.clone(); + for art in brushes.iter_mut().flat_map(|b| b.art_mut()) { + visit(art, f)?; + } + if brushes != original_brushes { + vectorcraft_brush::store(d, &brushes); + } + Ok(()) } fn text_mut(d: &mut Document, id: NodeId) -> Option<&mut vectorcraft_doc::TextObject> { @@ -327,16 +378,20 @@ fn uses_of(uses: &std::collections::HashMap, usize>, kind: Kind, } /// Update every user of `name` from `old` to `new` attributes (overrides kept). -fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) { +fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) -> Result<()> { let target = (name != kind.normal()).then_some(name.to_string()); - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); + let base = match kind { + Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?), + Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?), + }; + each_text_mut(d, &mut |t| { let mut changed = false; match kind { Kind::Char => { for r in &mut t.runs { if r.style.style_name == target { - r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new), new); + r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; } } @@ -344,7 +399,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map { for pa in t.para_styles_mut() { if pa.style_name == target { - *pa = restyle(pa, para_attrs, old, new); + *pa = restyle(pa, para_attrs, old, new, &base); changed = true; } } @@ -353,7 +408,8 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map Option Map { + new_style_attrs(s, if para { Kind::Para } else { Kind::Char }) +} + /// Whether the document has a character (`para`: paragraph) style `name`, and its attributes. pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option> { if para { Kind::Para } else { Kind::Char }.attrs(d, name) @@ -566,13 +627,16 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map, verb: &str) -> Result { let d = &s.doc()?.doc; let old = kind.attrs(d, name).ok_or_else(|| bad(&kind.cmd(verb), format!("no style `{name}`")))?; + if new_attrs == old { + return ok(); + } let name = name.to_string(); s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| { match kind.defs_mut(d).iter_mut().find(|s| s.name == name) { Some(def) => def.attrs = new_attrs.clone(), None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }), } - update_users(d, kind, &name, &old, &new_attrs); + update_users(d, kind, &name, &old, &new_attrs)?; Ok(()) })?; ok() @@ -590,6 +654,50 @@ fn set_attrs(s: &mut Session, p: &Value, kind: Kind) -> Result { redefine_to(s, kind, &name, attrs, "setAttrs") } +fn edit_style(s: &mut Session, p: &Value, kind: Kind) -> Result { + let c = kind.cmd("edit"); + let name = name_param(p, kind, "edit")?.to_string(); + let to = str_param(p, "to").ok_or_else(|| bad(&c, "missing `to`"))?.trim().to_string(); + let attrs = attrs_param(p, kind, "edit")?.ok_or_else(|| bad(&c, "missing `attrs`"))?; + let d = &s.doc()?.doc; + let old = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; + if name == kind.normal() { + return Err(bad(&c, format!("`{name}` can't be edited this way"))); + } + if to.is_empty() { + return Err(bad(&c, "give the style a name")); + } + if to != name && kind.attrs(d, &to).is_some() { + return Err(bad(&c, format!("a style named `{to}` already exists"))); + } + if to == name && attrs == old { + return ok(); + } + s.edit(if kind == Kind::Char { "Character Style Options" } else { "Paragraph Style Options" }, |d, _| { + if let Some(def) = kind.defs_mut(d).iter_mut().find(|def| def.name == name) { + def.name = to.clone(); + def.attrs = attrs.clone(); + } + update_users(d, kind, &name, &old, &attrs)?; + if to != name { + each_text_mut(d, &mut |t| { + let fix = |style_name: &mut Option| { + if style_name.as_deref() == Some(name.as_str()) { + *style_name = Some(to.clone()); + } + }; + match kind { + Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), + Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), + } + Ok(()) + })?; + } + Ok(()) + })?; + ok() +} + fn duplicate(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "duplicate")?.to_string(); let d = &s.doc()?.doc; @@ -618,8 +726,7 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(def) = kind.defs_mut(d).iter_mut().find(|s| s.name == name) { def.name = to.clone(); } - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + each_text_mut(d, &mut |t| { let fix = |n: &mut Option| { if n.as_deref() == Some(name.as_str()) { *n = Some(to.clone()); @@ -629,7 +736,8 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result { Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), } - } + Ok(()) + })?; Ok(()) })?; ok() @@ -653,8 +761,7 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result { } s.edit(if names.len() > 1 { "Delete Styles" } else { "Delete Style" }, |d, _| { kind.defs_mut(d).retain(|s| !names.contains(&s.name)); - for id in all_text(d) { - let Some(t) = text_mut(d, id) else { continue }; + each_text_mut(d, &mut |t| { let fix = |n: &mut Option| { if n.as_ref().is_some_and(|n| names.contains(n)) { *n = None; @@ -664,7 +771,8 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result { Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)), Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)), } - } + Ok(()) + })?; Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 2cdcaf77af..46b52346de 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -15,6 +15,233 @@ fn runs(s: &Session, id: u64) -> Vec { } } +fn embedded_style(s: &Session, container: &str) -> (Option, f64, Option) { + let d = &s.doc().unwrap().doc; + let brushes = vectorcraft_brush::library(d); + let roots: Vec<&Node> = match container { + "symbol" => d.symbols.iter().map(|s| &*s.art).collect(), + "pattern" => d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a)).collect(), + "graph" => d.graph_designs.iter().map(|g| &*g.art).collect(), + "brush" => brushes.iter().flat_map(|b| b.art()).collect(), + _ => panic!("unknown container"), + }; + let mut found = None; + for root in roots { + vectorcraft_doc::swatches::walk_with_masks(root, &mut |n| { + if let NodeKind::Text(t) = &n.kind { + found = Some((t.runs[0].style.style_name.clone(), t.runs[0].style.size, t.para.style_name.clone())); + } + }); + } + found.unwrap() +} + +fn embedded_style_session(kind: &str, container: &str) -> Session { + let (mut s, id) = session_with_text("Styled"); + s.execute(&format!("{kind}Style.new"), &json!({"name": "Body", "attrs": if kind == "char" { json!({"size": 24}) } else { json!({}) }})).unwrap(); + s.execute(&format!("{kind}Style.apply"), &json!({"name": "Body", "id": id})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + match container { + "symbol" => { + let symbol = s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [symbol["id"]]})).unwrap(); + } + "pattern" => { + s.execute("object.pattern.make", &json!({"edit": false})).unwrap(); + if s.doc().unwrap().doc.node(NodeId(id)).is_some() { + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + } + "graph" => { + s.execute("graph.design", &json!({"new": "Bar"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + "brush" => { + s.execute("brush.new", &json!({"type": "art", "name": "Lettering"})).unwrap(); + s.execute("edit.clear", &json!({"ids": [id]})).unwrap(); + } + _ => panic!("unknown container"), + } + s +} + +#[test] +fn character_style_options_update_embedded_art() { + for container in ["symbol", "pattern", "graph", "brush"] { + let mut s = embedded_style_session("char", container); + assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Body"), "{container}"); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + assert_eq!(embedded_style(&s, container).0.as_deref(), Some("Heading"), "{container}"); + assert_eq!(embedded_style(&s, container).1, 18.0, "{container}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "{container}"); + s.execute("edit.redo", &json!({})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.delete", &json!({"name": "Heading"})).unwrap(); + assert_eq!(embedded_style(&s, container).0, None, "{container}"); + assert_eq!(embedded_style(&s, container).1, 18.0, "{container}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{container}"); + } +} + +#[test] +fn character_style_edit_survives_canceling_pattern_edit() { + let mut s = embedded_style_session("char", "pattern"); + let name = s.doc().unwrap().doc.patterns[0].name.clone(); + s.execute("object.pattern.edit", &json!({"name": name})).unwrap(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + s.execute("object.pattern.cancel", &json!({})).unwrap(); + + assert_eq!(embedded_style(&s, "pattern").0.as_deref(), Some("Heading")); + assert_eq!(embedded_style(&s, "pattern").1, 18.0); +} + +#[test] +fn paragraph_style_rename_updates_symbol_art() { + let mut s = embedded_style_session("para", "symbol"); + assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Body")); + s.execute("paraStyle.rename", &json!({"name": "Body", "to": "Heading"})).unwrap(); + assert_eq!(embedded_style(&s, "symbol").2.as_deref(), Some("Heading")); +} + +#[test] +fn character_style_options_keep_text_free_layer_shared() { + let (mut s, id) = session_with_text("Styled"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + let empty_id = s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap(); + let before = s.doc().unwrap().doc.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap().clone(); + + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Heading", "attrs": {"size": 18}})).unwrap(); + + let d = &s.doc().unwrap().doc; + let after = d.layers.iter().find(|layer| layer.id == NodeId(empty_id)).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, after)); + assert_eq!(runs(&s, id)[0].style.style_name.as_deref(), Some("Heading")); + assert_eq!(runs(&s, id)[0].style.size, 18.0); +} + +#[test] +fn unchanged_style_options_keep_undo_and_redo_with_and_without_preview() { + for preview in [false, true] { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 18, "leading": null}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Other", "attrs": {}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let params = json!({"name": "Body", "to": " Body ", "attrs": {"size": 18.0, "leading": null}}); + if preview { + s.begin_interaction("Character Style Options").unwrap(); + s.preview("charStyle.edit", ¶ms).unwrap(); + s.commit_interaction().unwrap(); + } else { + s.execute("charStyle.edit", ¶ms).unwrap(); + } + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "preview={preview}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "preview={preview}"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "preview={preview}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Other")); + } +} + +#[test] +fn unchanged_style_attributes_keep_undo_and_redo_for_both_kinds() { + for (command, para) in [("charStyle", false), ("paraStyle", true)] { + let (mut s, _) = session_with_text("Text"); + let attrs = if para { json!({"space_before": 18}) } else { json!({"size": 18}) }; + s.execute(&format!("{command}.new"), &json!({"name": "Body", "attrs": attrs})).unwrap(); + s.execute(&format!("{command}.new"), &json!({"name": "Other", "attrs": {}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let attrs = if para { json!({"space_before": 18.0}) } else { json!({"size": 18.0}) }; + s.execute(&format!("{command}.setAttrs"), &json!({"name": "Body", "attrs": attrs})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{command}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{command}"); + assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{command}"); + } +} + +#[test] +fn character_style_options_edit_applies_to_users_and_is_one_saved_undo_step() { + let (mut s, id) = session_with_text("First second"); + s.execute("charStyle.new", &json!({"name":"Body", "attrs":{"size":24.0,"tracking":20.0,"baseline_shift":3.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":0, "end":5})).unwrap(); + s.execute("charStyle.apply", &json!({"name":"Body", "id":id, "start":6, "end":12})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id":id,"start":6,"end":12,"size":31.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("charStyle.edit", &json!({"name":"Body","to":"Text","attrs":{"size":18.0,"tracking":40.0,"baseline_shift":3.0}})).unwrap(); + let changed = s.doc().unwrap().doc.clone(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!( + runs(&s, id).iter().map(|r| (r.style.style_name.as_deref(), r.style.size, r.style.tracking)).collect::>(), + [(Some("Text"), 18.0, 40.0), (None, 12.0, 0.0), (Some("Text"), 31.0, 40.0)] + ); + let future = s.execute("text.create", &json!({"x":20,"y":90,"text":""})).unwrap()["id"].as_u64().unwrap(); + s.execute("charStyle.apply", &json!({"name":"Text","id":future})).unwrap(); + s.execute("text.editRange", &json!({"id":future,"start":0,"end":0,"insert":"Later"})).unwrap(); + assert_eq!((runs(&s, future)[0].style.size, runs(&s, future)[0].style.tracking), (18.0, 40.0)); + let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!( + saved.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs, + s.doc().unwrap().doc.char_styles.iter().find(|d| d.name == "Text").unwrap().attrs + ); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, changed); +} + +#[test] +fn editing_character_style_clears_removed_size_without_losing_local_override() { + let (mut s, id) = session_with_text("One two"); + s.execute("charStyle.setAttrs", &json!({"name": NORMAL_CHAR, "attrs": {"size": 15.0}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 31.0})).unwrap(); + s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {}})).unwrap(); + let r = runs(&s, id); + assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0)); +} + +#[test] +fn replacing_character_style_attrs_clears_removed_size() { + let (mut s, id) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {}})).unwrap(); + assert_eq!(runs(&s, id)[0].style.size, 12.0); +} + +#[test] +fn character_style_options_edit_validates_names_and_allows_case_changes() { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name":"Body","attrs":{"size":24.0}})).unwrap(); + s.execute("charStyle.new", &json!({"name":"Other","attrs":{}})).unwrap(); + for (name, to, message) in + [(super::NORMAL_CHAR, "New", "can't be edited this way"), ("Body", " ", "give the style a name"), ("Body", "Other", "already exists")] + { + let error = s.execute("charStyle.edit", &json!({"name":name,"to":to,"attrs":{}})).unwrap_err().to_string(); + assert!(error.contains(message), "{error}"); + } + s.execute("charStyle.edit", &json!({"name":"Body","to":"body","attrs":{"size":18.0}})).unwrap(); + s.execute("charStyle.edit", &json!({"name":"body","to":" body ","attrs":{"size":20.0}})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles.iter().find(|style| style.name == "body").unwrap().attrs["size"], json!(20.0)); +} + #[test] fn char_style_new_apply_range_redefine_keeps_overrides() { let (mut s, id) = session_with_text("Hello world"); @@ -293,10 +520,10 @@ fn auto_leading_redefine_keeps_overrides_and_history() { s.execute("text.setStyle", &json!({"ids": [linked], "leading": "auto"})).unwrap(); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"leading": 28}})).unwrap(); assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]); - // Omitting leading replaces the definition without resetting the text's leading. + // Omitting leading returns linked text to Auto and keeps local overrides. s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"tracking": 20}})).unwrap(); assert!(!s.doc().unwrap().doc.char_styles[0].attrs.contains_key("leading")); - assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [Some(28.0), None, Some(42.0)]); + assert_eq!(ids.map(|id| runs(&s, id)[0].style.leading), [None, None, Some(42.0)]); } } @@ -308,7 +535,7 @@ fn settable() -> std::collections::BTreeSet { /// New and Redefine capture every paragraph attribute. A paragraph style redefined from a /// paragraph at the defaults gives its paragraphs the defaults back where they had the old /// definition's values, and `setAttrs` with a default value does too; local overrides, and -/// attributes `setAttrs` leaves out, stay. +/// attributes `setAttrs` leaves out return to the base value. #[test] fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { use vectorcraft_doc::{Composer, HyphenationOptions}; @@ -335,11 +562,11 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() { assert_eq!(defined(&s, 0), settable::(), "Redefine captures every attribute"); s.execute("paraStyle.new", &json!({"name": "Copy", "id": local})).unwrap(); assert_eq!(defined(&s, 1), settable::(), "New captures every attribute"); - // Style options: a default value reaches the users too; an attribute left out stays as it is. + // Style options: a default value reaches users, and an attribute left out returns to base. s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"hyphenation": {"hyphen_limit": 3}, "composer": "singleLine"}})).unwrap(); assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::SingleLine; 3])); s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"composer": "everyLine"}})).unwrap(); - assert_eq!((limits(&s), composers(&s)), ([3, 3, 4], [Composer::EveryLine; 3])); + assert_eq!((limits(&s), composers(&s)), ([0, 0, 4], [Composer::EveryLine; 3])); assert_eq!(Value::Object(s.doc().unwrap().doc.para_styles[0].attrs.clone()), json!({"composer": "everyLine"})); } @@ -368,7 +595,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() { s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap(); assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3])); s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap(); - assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::RomanBaseline; 3])); + assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3])); assert_eq!(Value::Object(s.doc().unwrap().doc.char_styles[0].attrs.clone()), json!({"charAlign": "romanBaseline"})); } @@ -460,6 +687,20 @@ fn auto_leading_new_distinguishes_unset_attributes() { assert_eq!(s.doc().unwrap().doc.char_styles[2].attrs.get("leading"), Some(&Value::Null)); } +#[test] +fn optical_character_style_captures_and_redefines_automatic_mode() { + let (mut s, id) = session_with_text("III"); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "optical"})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Profile", "id": id})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(true))); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Profile", "id": id})).unwrap(); + assert!(runs(&s, id)[0].style.optical_kerning); + s.execute("text.setRangeStyle", &json!({"id": id, "kerning": "auto"})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "Profile", "id": id})).unwrap(); + assert_eq!(s.doc().unwrap().doc.char_styles[0].attrs.get("opticalKerning"), Some(&json!(false))); +} + #[test] fn paragraph_styles_and_survive_save() { let (mut s, id) = session_with_text("Body"); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index c6a33ffc66..ef448da9de 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -457,6 +457,31 @@ fn brush_unused_lists_the_brushes_no_stroke_paints_with() { assert_eq!(unused(&mut s), ["3 pt. Round", "6 pt. Flat", "Charcoal"]); } +/// A stroke in the tile that pattern editing's Cancel puts back counts as a use, as `brush.delete` +/// clears it there. +#[test] +fn brush_unused_counts_pattern_edit_originals() { + let mut s = session(); + let id = rect(&mut s, 10.0, 10.0, 40.0, 20.0); + s.execute("brush.apply", &json!({"name": "6 pt. Flat", "ids": [id.0]})).unwrap(); + let name = s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap()["name"].clone(); + s.execute("brush.remove", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.pattern.edit", &json!({ "name": name })).unwrap(); + // The tile's copies in the editing layer are selected; only the tile kept for Cancel paints with the brush. + s.execute("brush.remove", &json!({})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let original = d.pattern_edit.as_ref().and_then(|pe| pe.original.as_ref()).expect("pattern edit original"); + assert_eq!(original.art.first().and_then(|n| n.appearance.stroke()).and_then(|k| k.brush.as_deref()), Some("6 pt. Flat")); + for pattern in &mut d.patterns { + for art in &mut pattern.art { + if let Some(stroke) = std::sync::Arc::make_mut(art).appearance.stroke_mut() { + stroke.brush = None; + } + } + } + assert!(!unused(&mut s).contains(&"6 pt. Flat".to_string())); +} + /// A brush counts as used when a stroke paints with it in an opacity mask, a symbol, a graph /// design, a pattern tile, a graphic style, or the art of a brush that is used. The art of a brush /// that is not used, its own strokes included, does not count. @@ -807,6 +832,194 @@ fn art_brush_options_keep_the_scale_fields_an_edit_leaves_out() { assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap()["scale"], json!({"mode": "stretch"})); } +#[test] +fn pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side() { + use std::sync::Arc; + use vectorcraft_doc::{PatternDef, StrokeLayer}; + use vectorcraft_geom::BezPath; + + let mut s = session(); + s.edit("Pattern", |d, _| { + let art = + Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), vectorcraft_doc::Appearance::default_art()); + d.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Plain Tiles", "params":{"side":side}})).unwrap(); + let original = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for choice in ["none", "Missing"] { + let error = s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":choice}})).unwrap_err().to_string(); + assert!(error.contains(if choice == "none" { "You must choose a side pattern." } else { "no pattern named" }), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(), original); + } + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"Wide", "fit":"addSpace"}})).unwrap(); + let saved = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + assert_eq!(saved["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + assert_eq!(saved["side_swatch"], "Wide"); + let brush: vectorcraft_brush::Brush = serde_json::from_value(saved).unwrap(); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + let pieces = vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &brush, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0), + ); + assert_eq!(pieces.len(), 10, "10 pt tile frame repeats ten times along 100 pt"); + assert!(pieces[0].geometric_bounds().unwrap().width() >= 29.9, "whole 30 pt art is copied"); + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"inner_corner_tile":"Wide", "outer_corner_tile":"none"}})).unwrap(); + let corners: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap(); + let mut fallback = corners.clone(); + if let (vectorcraft_brush::BrushKind::Pattern(actual), vectorcraft_brush::BrushKind::Pattern(legacy)) = (&corners.kind, &mut fallback.kind) { + assert_eq!(actual.outer_source, Some(vectorcraft_brush::CornerSource::None)); + assert!(actual.inner_corner.is_some()); + legacy.outer_source = None; + } + let square = |clockwise: bool| { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + if clockwise { + for point in [(100.0, 0.0), (100.0, 100.0), (0.0, 100.0)] { + p.line_to(point); + } + } else { + for point in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] { + p.line_to(point); + } + } + p.close_path(); + p + }; + let stroke = StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0); + assert!( + [false, true].into_iter().any(|clockwise| { + let path = square(clockwise); + vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &corners, &path, &stroke) + != vectorcraft_brush::stroke_pieces(&s.doc().unwrap().doc, &fallback, &path, &stroke) + }), + "explicit outer None omits the inner corner art on outer turns" + ); + let borrowed_art = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["inner_corner"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Borrowed Corner", "params":{"side":original["side"], "inner_corner":borrowed_art}})) + .unwrap(); + s.execute("brush.options", &json!({"name":"Borrowed Corner", "params":{"outer_corner_tile":"original", "inner_corner_tile":"none"}})).unwrap(); + let borrowed = s.execute("brush.get", &json!({"name":"Borrowed Corner"})).unwrap(); + assert!(borrowed["outer_corner"].is_object()); + assert_eq!(borrowed["inner_source"], "none"); + s.edit("Delete pattern", |d, _| { + d.patterns.clear(); + Ok(()) + }) + .unwrap(); + let after: vectorcraft_brush::Brush = serde_json::from_value(s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()).unwrap(); + assert_eq!( + vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &after, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) + ) + .len(), + 10 + ); + let copied = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap()["side"].clone(); + s.execute("brush.options", &json!({"name":"Plain Tiles", "params":{"side_tile":"original"}})).unwrap(); + let original_choice = s.execute("brush.get", &json!({"name":"Plain Tiles"})).unwrap(); + assert_eq!(original_choice["side"], copied); + assert!(original_choice.get("side_swatch").is_none()); +} + +#[test] +fn pattern_original_corner_keeps_borrowed_art_and_frame_when_source_is_cleared() { + let mut s = session(); + let chain = s.execute("brush.get", &json!({"name": "Chain"})).unwrap(); + let art = chain["outer_corner"].clone(); + let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0)); + for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] { + let source_art = format!("{source}_corner"); + let source_frame = format!("{source_art}_frame"); + let borrowed_art = format!("{borrowed}_corner"); + let borrowed_frame = format!("{borrowed_art}_frame"); + let source_tile = format!("{source_art}_tile"); + let borrowed_tile = format!("{borrowed_art}_tile"); + s.execute("brush.new", &json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap(); + s.execute("brush.options", &json!({"name":name, "params":{source_tile:"none", borrowed_tile:"original"}})).unwrap(); + let saved = s.execute("brush.get", &json!({"name":name})).unwrap(); + assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} art"); + assert_eq!(saved[&borrowed_frame], frame, "{borrowed} frame"); + assert_eq!(saved[format!("{source}_source")], "none"); + } +} + +#[test] +fn pattern_tile_object_selects_reserved_swatch_names() { + use std::sync::Arc; + use vectorcraft_doc::PatternDef; + + let mut s = session(); + let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"]; + s.edit("Patterns", |doc, _| { + for name in names { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) }); + } + Ok(()) + }) + .unwrap(); + let before = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(); + for invalid in [json!({}), json!({"pattern": null}), json!({"pattern": 1})] { + let error = s.execute("brush.options", &json!({"name":"Diamonds", "params":{"side_tile":invalid}})).unwrap_err().to_string(); + assert!(error.contains("invalid pattern tile choice"), "{error}"); + assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(), before); + } + let slots = ["side_tile", "outer_corner_tile", "inner_corner_tile", "start_tile", "end_tile"]; + for (slot, name) in slots.into_iter().zip(names) { + s.execute("brush.options", &json!({"name":"Diamonds", "params":{(slot):{"pattern":name}}})).unwrap(); + } + let saved = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap(); + for (art, name) in ["side", "outer_corner", "inner_corner", "start", "end"].into_iter().zip(names) { + assert_eq!(saved[format!("{art}_swatch")], name); + assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + } + s.execute("brush.options", &json!({"name":"Diamonds", "params":{"outer_corner_tile":{"pattern":"autoOverlap"}}})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["outer_corner_swatch"], "autoOverlap"); +} + +#[test] +fn pattern_end_tile_none_choices_leave_side_art_at_both_path_ends() { + use vectorcraft_doc::StrokeLayer; + use vectorcraft_geom::BezPath; + + let mut s = session(); + let side = s.execute("brush.get", &json!({"name":"Diamonds"})).unwrap()["side"].clone(); + let cap = s.execute("brush.get", &json!({"name":"Chain"})).unwrap()["outer_corner"].clone(); + s.execute("brush.new", &json!({"type":"pattern", "name":"Capped", "params":{"side":side, "start":cap, "end":cap}})).unwrap(); + s.execute("brush.options", &json!({"name":"Capped", "params":{"start_tile":"none", "end_tile":"none"}})).unwrap(); + let def = s.execute("brush.get", &json!({"name":"Capped"})).unwrap(); + assert!(def.get("start").is_none() && def.get("end").is_none()); + let brush: vectorcraft_brush::Brush = serde_json::from_value(def).unwrap(); + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + let pieces = vectorcraft_brush::stroke_pieces( + &s.doc().unwrap().doc, + &brush, + &path, + &StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0), + ); + let bounds = pieces.iter().fold(None, |bounds, node| vectorcraft_geom::union_opt(bounds, node.geometric_bounds())).unwrap(); + assert!((bounds.x0 - 0.0).abs() < 1e-6 && (bounds.x1 - 100.0).abs() < 1e-6, "{bounds:?}"); +} + // ---------- symbols ---------- fn make_symbol(s: &mut Session) -> (NodeId, String, Rect) { diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index bb9a9ac0f9..bcd590c2d4 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -379,6 +379,38 @@ fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() { assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]); } +#[test] +fn eps_export_writes_a_colorized_image_in_its_spot_ink_without_flattening() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [id.0]})).unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let ps = String::from_utf8_lossy(&bytes); + assert!(ps.contains("imagemask") && ps.contains("/Separation (Ink) cvn"), "the image prints on the Ink plate"); + assert!(ps.contains("%%DocumentCustomColors: (Ink)")); + + // Opacity still flattens it. + s.execute("transparency.set", &json!({"ids": [id.0], "opacity": 50})).unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); +} + +#[test] +fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() { + let mut s = session(); + let rgb = png(image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(2, 1, vec![0, 128, 255, 255, 0, 0]).unwrap())); + let id = image(&mut s, "rgb", rgb); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/engine/src/tests/containers.rs b/crates/engine/src/tests/containers.rs index aa72ebeccf..1b147ecc1e 100644 --- a/crates/engine/src/tests/containers.rs +++ b/crates/engine/src/tests/containers.rs @@ -69,6 +69,28 @@ fn a_group_fill_paints_both_members_and_the_contents_slot_moves() { assert!(s.execute("appearance.moveItem", &json!({"from": "contents", "to": 1})).is_err()); } +#[test] +fn ungroup_leaves_the_groups_opacity_with_the_group() { + let mut s = session(); + let red = id_of(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 40}))); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let blue = id_of(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 20, "width": 60, "height": 40}))); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "object.setProps", json!({"ids": [blue.0], "opacity": 40})); + run(&mut s, "select.set", json!({"ids": [red.0, blue.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "object.setProps", json!({"ids": [g.0], "opacity": 50})); + run(&mut s, "object.ungroup", json!({})); + // Each member keeps its own opacity: the red square is opaque again and the blue one stays at 40%. + assert!((node(&s, red).opacity - 1.0).abs() < 1e-6, "{}", node(&s, red).opacity); + assert!((node(&s, blue).opacity - 0.4).abs() < 1e-6, "{}", node(&s, blue).opacity); + assert_eq!(pixel(&s, 40, 40), RED); + // One undo step brings the group back at 50%. + run(&mut s, "edit.undo", json!({})); + assert!((node(&s, g).opacity - 0.5).abs() < 1e-6); + assert!((node(&s, red).opacity - 1.0).abs() < 1e-6); +} + #[test] fn appearance_commands_target_the_object_or_its_contents() { let mut s = session(); diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index bdd3455f7f..6895d74a07 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -135,6 +135,133 @@ fn front_and_back_choose_the_member_where_three_objects_overlap() { assert!(e.to_string().contains("999"), "{e}"); } +/// The rings with a green bar across their top crossing, in front of both, made into an +/// Intertwine group: (group, a, b, c). A, B and C overlap at (50, 30); only A and B at (50, 70). +fn rings_and_bar(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let (a, b) = rings(s); + let c = id_of(&s.execute("shape.rectangle", &json!({"x": 46, "y": 20, "width": 8, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#00ff00"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [c.0], "none": true})).unwrap(); + select(s, &[a, b, c]); + let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap()); + (g, a, b, c) +} + +/// The members of the overlap area of Intertwine group `g` at (x, y), in the order they are drawn +/// there, bottom first. +fn order_at(d: &Document, g: NodeId, x: f64, y: f64) -> Vec { + use vectorcraft_tools::intertwine::{drawn_order, face_at, faces}; + let children = d.node(g).unwrap().children().unwrap(); + let face = face_at(&faces(children), vectorcraft_geom::Point::new(x, y)).unwrap(); + drawn_order(children, &face).into_iter().map(|i| children[i].id).collect() +} + +/// Bring Forward and Send Backward move an object one place among the objects of one overlap +/// area, keeping the others' order, so every order of three objects can be set there (C, B, A +/// included); the other areas stay as they are. +#[test] +fn forward_and_backward_move_an_object_one_place_in_an_area() { + let mut s = session(); + let (g, a, b, c) = rings_and_bar(&mut s); + let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0); + let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(1), &json!([c.0]))); + assert_eq!(order(&s), [b, a, c]); + arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0})); + assert_eq!(order(&s), [b, c, a]); + assert!(red(&render(&s), 50, 30), "A is on top"); + let v = arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0})); + assert_eq!(v["top"], json!([a.0])); + assert_eq!(order(&s), [c, b, a], "the reverse of the group's order"); + assert_eq!(hit(&s, 50.0, 30.0), Some(a), "a click picks the object drawn on top"); + // Without a member: forward moves the object right below the top, backward the top one. + arrange(&mut s, json!({"at": [50, 30], "order": "backward"})); + assert_eq!(order(&s), [c, a, b]); + assert!(blue(&render(&s), 50, 30)); + assert_eq!(hit(&s, 50.0, 30.0), Some(b)); + arrange(&mut s, json!({"at": [50, 30], "order": "forward"})); + assert_eq!(order(&s), [c, b, a]); + // Bring to Front and Send to Back keep the order of the others. + arrange(&mut s, json!({"at": [50, 30], "order": "front", "member": c.0})); + assert_eq!(order(&s), [b, a, c]); + arrange(&mut s, json!({"at": [50, 30], "order": "back", "member": a.0})); + assert_eq!(order(&s), [a, b, c]); + // The crossing where only the rings overlap is as it was. + assert_eq!(order_at(&s.doc().unwrap().doc, g, 50.0, 70.0), [a, b]); + assert!(blue(&render(&s), 50, 70)); + // There only the rings count: forward moves A over B, and C is not in that area. + let v = arrange(&mut s, json!({"at": [50, 70], "order": "forward"})); + assert_eq!(v["top"], json!([a.0])); + assert!(red(&render(&s), 50, 70)); + let e = s.execute("object.intertwine.arrange", &json!({"at": [50, 70], "order": "backward", "member": c.0})).unwrap_err(); + assert!(e.to_string().contains("not in the overlap"), "{e}"); + assert_eq!(order(&s), [a, b, c]); +} + +/// An object already at the end it is moved to is not moved: no area changes and no undo step is +/// recorded. One move is one undo step, and undo, redo and a saved file keep the order. +#[test] +fn a_move_that_changes_nothing_records_nothing_and_orders_survive_undo_and_save() { + let mut s = session(); + let (g, a, b, c) = rings_and_bar(&mut s); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + for (order, member) in [("forward", c), ("front", c), ("backward", a), ("back", a)] { + let v = arrange(&mut s, json!({"at": [50, 30], "order": order, "member": member.0})); + assert_eq!((&v["count"], &v["top"]), (&json!(0), &json!([])), "{order}"); + } + assert_eq!(undo(&s), before, "nothing to undo"); + arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": b.0})); + arrange(&mut s, json!({"at": [50, 30], "order": "backward", "member": c.0})); + arrange(&mut s, json!({"at": [50, 30], "order": "forward", "member": a.0})); + assert_eq!(undo(&s), before + 3, "one undo step a move"); + let order = |s: &Session| order_at(&s.doc().unwrap().doc, g, 50.0, 30.0); + assert_eq!(order(&s), [c, b, a]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(order(&s), [c, a, b]); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(order(&s), [c, b, a]); + let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "rings.vectorcraft", "dataBase64": data})).unwrap(); + assert_eq!(order_at(&o.doc().unwrap().doc, g, 50.0, 30.0), [c, b, a]); + assert!(red(&render(&o), 50, 30) && blue(&render(&o), 50, 70)); + // Expand draws the same. + s.execute("object.expand", &json!({"fill": false, "stroke": false})).unwrap(); + assert!(red(&render(&s), 50, 30) && blue(&render(&s), 50, 70)); +} + +/// Where three or more objects overlap, hovering highlights the outline of the object nearest to +/// the pointer. +#[test] +fn hovering_where_three_overlap_highlights_the_nearest_object() { + use kurbo::Shape; + let mut s = session(); + let view = ViewInfo::default(); + // Squares from x = 0, 20 and 40, 60 wide: all three overlap from x = 40 to 60. + let ids: Vec = + [0, 20, 40].iter().map(|x| id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 60, "height": 60})).unwrap())).collect(); + select(&mut s, &ids); + s.execute("object.intertwine.make", &json!({})).unwrap(); + let highlighted = |s: &mut Session, x: f64| { + s.pointer(&vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Move, x, 30.0), view).unwrap(); + let o = s.overlays(view); + let [vectorcraft_tools::Overlay::Path { path, .. }] = o.as_slice() else { panic!("one highlight: {o:?}") }; + let r = path.bounding_box(); + (r.x0, r.x1) + }; + // Within the half point a 1 pt stroke reaches past each edge. + let near = |(x0, x1): (f64, f64), (e0, e1): (f64, f64)| (x0 - e0).abs() <= 0.6 && (x1 - e1).abs() <= 0.6; + // By the left edge of the third square, then by the right edge of the first one. + let h = highlighted(&mut s, 41.0); + assert!(near(h, (40.0, 100.0)), "{h:?}"); + let h = highlighted(&mut s, 59.0); + assert!(near(h, (0.0, 60.0)), "{h:?}"); + // Where two overlap, the area is highlighted. + let h = highlighted(&mut s, 30.0); + assert!(near(h, (20.0, 40.0)), "{h:?}"); +} + #[test] fn release_gives_the_objects_back_as_they_were() { let mut s = session(); diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index 7ac5c3c5c9..90c728a2fc 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -546,7 +546,7 @@ fn a_colorized_grayscale_image_pattern_fill_is_expanded() { let keys = crate::cmd::flatten::see_through_images(d); assert!(keys.is_empty()); let layer = d.layers[0].id; - assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1); + assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1); let mut patterns = 0; let mut tile_images = 0; d.walk(|n| { @@ -688,7 +688,7 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); let keys = crate::cmd::flatten::see_through_images(d); let layer = d.layers[0].id; - assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1); + assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys, &|_, _| true).unwrap(), 1); let mut patterns = vec![]; let mut images = 0; d.walk(|n| { @@ -704,3 +704,304 @@ fn only_the_transparent_pattern_fill_of_a_leaf_is_expanded() { assert_eq!(patterns.len(), 1, "{patterns:?}"); assert!(images > 0); } + +/// A pattern fill whose expanded art would hold more objects than the budget stays a pattern fill: +/// the 32 pt tiles over the 128 pt square are 25 copies of the tile art's 3 objects, which are not +/// made with a smaller budget, and the clip group around them counts too. +#[test] +fn a_transparent_image_pattern_past_the_budget_stays() { + let expand = |budget: usize| { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + assert_eq!(s.doc().unwrap().doc.patterns[0].art.iter().map(|a| a.count_with_masks()).sum::(), 3); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let keys = crate::cmd::flatten::see_through_images(d); + let layer = d.layers[0].id; + let before = d.layers[0].count_with_masks(); + let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap(); + // The objects the expansion made, with the square it replaced. + (n, images(d).0, d.layers[0].count_with_masks() + 1 - before) + }; + let (n, tiles, made) = expand(usize::MAX); + assert_eq!((n, tiles), (1, 25)); + assert!(made > 75, "{made}"); + assert_eq!(expand(made), (1, 25, made)); + assert_eq!(expand(made - 1).0, 0); + assert_eq!(expand(74).0, 0); +} + +/// On a shape with two transparent image pattern fills, both expand with a budget their tiles and +/// the group around them fit, and one expands with one object less. +#[test] +fn two_transparent_image_pattern_fills_expand_within_the_budget() { + let expand = |budget: usize| { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut square = None; + d.walk(|n| { + if n.appearance.items.iter().any( + |i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(f.paint, vectorcraft_color::Paint::Pattern { .. })), + ) { + square = Some(n.id); + } + }); + let n = d.node_mut(square.unwrap()).unwrap(); + assert_eq!(n.appearance.items.len(), 1); + let fill = n.appearance.items[0].clone(); + n.appearance.items.push(fill); + let keys = crate::cmd::flatten::see_through_images(d); + let layer = d.layers[0].id; + let before = d.layers[0].count_with_masks(); + let n = crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &keys, &|_, _| true, budget).unwrap(); + (n, images(d).0, d.layers[0].count_with_masks() + 1 - before) + }; + let (n, tiles, made) = expand(usize::MAX); + assert_eq!((n, tiles), (1, 50)); + assert_eq!(expand(made), (1, 50, made)); + assert_eq!(expand(made - 1).1, 25); +} + +#[test] +fn pdf13_flattens_see_through_pattern_tile_images() { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn pdf13_flattens_colorized_pattern_tile_images() { + let mut s = colorized_pattern_over_blue(); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_level3_writes_see_through_pattern_tile_images() { + let mut s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 255, 255, 0]), 1.0); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let page = &s.doc().unwrap().doc; + let after = [colour_at(page, 72.0, 72.0), colour_at(page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn eps_writes_colorized_pattern_tile_images_in_their_colors() { + let mut s = colorized_pattern_over_blue(); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn flattening_that_keeps_colorize_leaves_colorized_pattern_tile_images_alone() { + let s = colorized_pattern_over_blue(); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + let o = crate::cmd::FlattenOptions { keeps_colorize: true, ..Default::default() }; + assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none(), "the pattern isn't expanded for a colorize paint alone"); +} + +/// EPS export expands pattern tile images once: flattening the expanded +/// document leaves the patterns the expansion kept, past its object limit, as they are. +#[test] +fn flattening_an_expanded_document_does_not_expand_patterns_again() { + let s = colorized_pattern_over_blue(); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_expanded(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); +} + +#[test] +fn eps_flattens_colorized_image_in_a_see_through_pattern_tile_group_and_warns() { + let mut s = colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let id = d.alloc_id(); + let art = std::mem::take(&mut d.patterns[0].art); + let mut group = vectorcraft_doc::Node::group(id, art); + group.opacity = 0.5; + d.patterns[0].art.push(std::sync::Arc::new(group)); + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + let after = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn postscript_print_warns_for_colorized_pattern_tile_image() { + let mut s = colorized_pattern_over_blue(); + let r = s.execute("file.print", &json!({"format": "postscript"})).unwrap(); + assert!(warnings(&r).iter().any(|w| w.contains("transparency is flattened")), "{:?}", warnings(&r)); +} + +#[test] +fn eps_pattern_does_not_flatten_a_separate_see_through_image() { + let mut output = vec![]; + for tile in [checker([0, 200, 0, 255], [255, 230, 0, 255]), checker([0, 200, 0, 255], [255, 255, 255, 0])] { + let mut s = pattern_over_blue(&tile, 1.0); + s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let p = json!({"name": "i.png", "dataBase64": vectorcraft_format::base64_encode(&png(20, 20, [0, 0, 0, 128])), "at": [20, 20]}); + s.execute("file.place", &p).unwrap(); + let r = + s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": true, "level": 3, "flattenerPreset": "high"})).unwrap(); + let image_warning = warnings(&r).iter().any(|w| w.contains("partly transparent")); + s.execute("document.open", &json!({"name": "p.eps", "dataBase64": r["dataBase64"], "editingData": false})).unwrap(); + output.push((colour_at(&s.doc().unwrap().doc, 20.0, 20.0), image_warning)); + } + assert_eq!(output[0], output[1], "EPS layer image changed when a see-through pattern tile was present: {output:?}"); +} + +#[test] +fn opaque_pattern_tile_images_do_not_change_during_export_flattening() { + let s = pattern_over_blue(&checker([0, 200, 0, 255], [255, 230, 0, 255]), 1.0); + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); + let o = crate::cmd::FlattenOptions { no_transparency: Some(crate::cmd::flatten::see_through_images(d)), ..Default::default() }; + assert!(crate::cmd::flatten::flatten_document(d, &o).unwrap().is_none()); +} + +/// The id of the square [`pattern_over_blue`] fills with its pattern. +fn pattern_square(s: &Session) -> vectorcraft_doc::NodeId { + let mut id = None; + s.doc().unwrap().doc.walk(|n| { + if n.appearance.items.iter().any(|i| matches!(i.paint(), vectorcraft_color::Paint::Pattern { .. })) { + id = Some(n.id); + } + }); + id.unwrap() +} + +/// PDF 1.3 draws `s` as the canvas draws it at two points of the pattern square. +fn assert_pdf13_draws_pattern_square_as_canvas(s: &mut Session) { + let before = [colour_at(&s.doc().unwrap().doc, 72.0, 72.0), colour_at(&s.doc().unwrap().doc, 88.0, 72.0)]; + let r = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let page = vectorcraft_pdf::import(&bytes).unwrap(); + let after = [colour_at(&page, 72.0, 72.0), colour_at(&page, 88.0, 72.0)]; + for (a, b) in before.iter().zip(after) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 4), "before {before:?} after {after:?}"); + } +} + +#[test] +fn pdf13_flattens_colorized_pattern_tile_images_in_a_repeat() { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap(); + assert!(s.doc().unwrap().doc.layers[0].count() > 3); + let d = &s.doc().unwrap().doc; + let mut repeats = 0; + d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_)))); + assert_eq!(repeats, 1); + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +/// A repeat whose art would take the expanded art past the budget stays live. +#[test] +fn a_repeat_past_the_budget_stays_live() { + for (budget, live) in [(1, 1), (usize::MAX, 0)] { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("object.repeat.grid", &json!({"ids": [square.0]})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let layer = d.layers[0].id; + crate::cmd::expand::expand_transparent_image_patterns_within(d, layer, &Default::default(), &|_, _| true, budget).unwrap(); + let mut repeats = 0; + d.walk(|n| repeats += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Repeat(_)))); + assert_eq!(repeats, live, "budget {budget}"); + } +} + +/// [`colorized_pattern_over_blue`] with the square filled with a pattern named `outer` whose tile +/// art is a 32 pt square filled with the colorized image pattern. +fn nested_colorized_pattern_over_blue() -> Session { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.patterns[0].name.clone(); + let rect = d.layers[0].children().unwrap().last().unwrap().id; + let mut tile = d.remove(rect).unwrap(); + let paint = vectorcraft_color::Paint::Pattern { pattern: inner, xf: Default::default() }; + let tile_node = std::sync::Arc::make_mut(&mut tile); + tile_node.appearance.items.retain(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(_))); + for i in &mut tile_node.appearance.items { + if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i { + f.paint = paint.clone(); + } + } + let mut outer = d.patterns[0].clone(); + outer.name = "outer".into(); + outer.art = vec![tile]; + d.patterns.push(outer); + for i in &mut d.node_mut(square).unwrap().appearance.items { + if let vectorcraft_doc::appearance::AppearanceItem::Fill(f) = i { + f.paint = vectorcraft_color::Paint::Pattern { pattern: "outer".into(), xf: Default::default() }; + } + } + s +} + +#[test] +fn pdf13_flattens_colorized_image_in_a_pattern_nested_in_tile_art() { + let mut s = nested_colorized_pattern_over_blue(); + assert_eq!(colour_at(&s.doc().unwrap().doc, 72.0, 72.0), [255, 0, 0]); + assert!(crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &crate::cmd::FlattenOptions::default()).unwrap().is_some()); + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn flattening_skips_a_pattern_nested_in_hidden_tile_art() { + let mut s = nested_colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let outer = d.pattern_mut("outer").unwrap(); + std::sync::Arc::make_mut(&mut outer.art[0]).visible = false; + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none()); +} + +#[test] +fn pdf13_leaves_a_hidden_shape_with_a_colorized_pattern_tile_image_hidden() { + let mut s = colorized_pattern_over_blue(); + let square = pattern_square(&s); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(square).unwrap().visible = false; + assert_pdf13_draws_pattern_square_as_canvas(&mut s); +} + +#[test] +fn flattening_skips_pattern_tile_images_on_hidden_and_template_layers() { + for template in [false, true] { + let mut s = colorized_pattern_over_blue(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let layer = std::sync::Arc::make_mut(&mut d.layers[0]); + match &mut layer.kind { + vectorcraft_doc::NodeKind::Layer { template: t, .. } if template => *t = true, + _ => layer.visible = false, + } + let d = &s.doc().unwrap().doc; + assert!(crate::cmd::flatten::flatten_document(d, &crate::cmd::FlattenOptions::default()).unwrap().is_none(), "template {template}"); + } +} diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index a3b9f132b5..b46e5b0d0f 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -927,6 +927,32 @@ fn mesh_add_line_and_delete_point() { assert!(s.execute("object.mesh.deletePoint", &json!({"id": a.0, "index": 0})).is_err(), "corner lines can't go"); } +/// A Mesh tool click that hits a mesh's edge from just outside it adds a mesh line at the +/// nearest point of the edge; `tolerance` gives `object.mesh.addLine` the same reach. +#[test] +fn mesh_add_line_on_the_edge_from_just_outside() { + use crate::tooling::ViewInfo; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("mesh", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 99.0, 160.0), v).unwrap(); + } + let m = mesh_of(&s, a); + assert_eq!((m.rows, m.cols), (2, 1), "a row through the left edge"); + assert!(m.points.iter().any(|q| q.p.distance(Point::new(100.0, 160.0)) < 0.5), "{:?}", m.points.iter().map(|q| q.p).collect::>()); + let r = s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 202, "tolerance": 3})).unwrap(); + let m = mesh_of(&s, a); + assert_eq!((m.rows, m.cols), (2, 2), "a column through the bottom edge"); + assert!(m.points[r["index"].as_u64().unwrap() as usize].p.distance(Point::new(140.0, 200.0)) < 0.5); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 202})).is_err(), "no tolerance: outside"); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 140, "y": 210, "tolerance": 3})).is_err(), "past the tolerance"); +} + /// A mesh point `index`, and `rows`, `cols` or `columns` for Create Gradient Mesh, that is not a /// whole number is an error that changes nothing; 4.0 names point 4. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ff11009b16..91194b2730 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -316,137 +316,347 @@ fn shown_and_locked(s: &Session, id: NodeId) -> (bool, bool) { (n.visible, n.locked) } -/// Each of `commands` is off in isolation mode: the command list reports it disabled, its error -/// names isolation mode, and so does the error of a call that gives the selection as `ids` (for a -/// command that takes them). -fn off_in_isolation(s: &mut Session, commands: &[&str]) { - let ids: Vec = selected(s).iter().map(|i| i.0).collect(); - for c in commands { - let spec = find_command(c).unwrap(); - assert_eq!(spec.info(s).disabled_reason.as_deref(), Some("exit isolation mode first"), "{c}"); - let given = cmd::params::takes_key(spec.params, "ids").then(|| json!({"ids": ids})); - for p in std::iter::once(json!({})).chain(given) { - let e = s.execute(c, &p).unwrap_err().to_string(); - assert!(e.contains("exit isolation mode first"), "{c} {p}: {e}"); - } - } -} - -/// In isolation mode, Lock › Selection and Hide › Selection are off and change nothing, in an -/// isolated group and in an isolated compound path with one of its paths selected. After Exit -/// Isolation Mode they lock and hide again. -#[test] -fn lock_and_hide_selection_are_off_in_isolation_mode() { - let mut s = session(); - let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); - let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); - sel(&mut s, &[a, b]); - let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0); - let hole = rect(&mut s, 120.0, 120.0, 20.0, 20.0); - sel(&mut s, &[outer, hole]); - let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); - let ids = [a, b, g, outer, hole, compound]; - let commands = ["object.lock", "object.hide"]; - for (isolated, member) in [(g, a), (compound, hole)] { - s.execute("object.isolate", &json!({"id": isolated.0})).unwrap(); - sel(&mut s, &[member]); - off_in_isolation(&mut s, &commands); - for id in ids { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?} in isolation of {isolated:?}"); - } - assert_eq!(selected(&s), [member]); - s.execute("object.exitIsolation", &json!({})).unwrap(); - } - sel(&mut s, &[a]); - s.execute("object.lock", &json!({})).unwrap(); - sel(&mut s, &[outer]); - s.execute("object.hide", &json!({})).unwrap(); - assert_eq!(shown_and_locked(&s, a), (true, true)); - assert_eq!(shown_and_locked(&s, compound), (false, false)); -} - -/// In isolation mode, Unlock All and Show All are off: the locked and the hidden objects outside -/// and inside the isolated group stay as they are. Pattern editing mode and opacity mask editing -/// are not isolation mode for them. -#[test] -fn unlock_all_and_show_all_are_off_in_isolation_mode() { - let mut s = session(); - let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); - let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); - let c = rect(&mut s, 40.0, 0.0, 10.0, 10.0); - sel(&mut s, &[a, b, c]); - let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let locked = rect(&mut s, 100.0, 0.0, 10.0, 10.0); - let hidden = rect(&mut s, 120.0, 0.0, 10.0, 10.0); - s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); - s.execute("layer.setProps", &json!({"id": hidden.0, "visible": false})).unwrap(); - s.execute("layer.setProps", &json!({"id": b.0, "locked": true})).unwrap(); - s.execute("layer.setProps", &json!({"id": c.0, "visible": false})).unwrap(); - s.execute("object.isolate", &json!({"id": g.0})).unwrap(); - sel(&mut s, &[a]); - off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]); - for (id, want) in [(locked, (true, true)), (hidden, (false, false)), (b, (true, true)), (c, (false, false))] { - assert_eq!(shown_and_locked(&s, id), want, "{id:?}"); - } - s.execute("object.exitIsolation", &json!({})).unwrap(); - s.execute("object.unlockAll", &json!({})).unwrap(); - s.execute("object.showAll", &json!({})).unwrap(); - for id in [locked, hidden, b, c] { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}"); - } - - // Pattern editing mode: the tile's art hides and shows again. - let r = rect(&mut s, 300.0, 300.0, 10.0, 10.0); - sel(&mut s, &[r]); - s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); - let tile = selected(&s); - s.execute("object.hide", &json!({})).unwrap(); - assert!(!node(&s, tile[0]).visible, "hidden in pattern editing mode"); - s.execute("object.showAll", &json!({})).unwrap(); - assert!(node(&s, tile[0]).visible, "shown in pattern editing mode"); - // An object isolated inside pattern editing mode is isolation mode again. - s.execute("object.isolate", &json!({"id": tile[0].0})).unwrap(); - sel(&mut s, &[tile[0]]); - off_in_isolation(&mut s, &["object.unlockAll", "object.showAll"]); - s.execute("object.pattern.cancel", &json!({})).unwrap(); - - // Opacity mask editing: the mask's art locks and unlocks again. - let obj = rect(&mut s, 0.0, 300.0, 200.0, 200.0); - let m = rect(&mut s, 0.0, 300.0, 100.0, 200.0); - sel(&mut s, &[obj, m]); - s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); - s.execute("transparency.editOpacityMask", &json!({})).unwrap(); - let mask = selected(&s); - s.execute("object.lock", &json!({})).unwrap(); - assert!(node(&s, mask[0]).locked, "locked in opacity mask editing"); - s.execute("object.unlockAll", &json!({})).unwrap(); - assert!(!node(&s, mask[0]).locked, "unlocked in opacity mask editing"); -} - -/// In isolation mode, Lock › All Artwork Above, Lock › Other Layers, Hide › All Artwork Above and -/// Hide › Other Layers are off: the art above and the other layer stay as they are. -#[test] -fn lock_and_hide_above_and_other_layers_are_off_in_isolation_mode() { +/// Check command enablement, targets, selection and history inside an isolated group. +fn check_group_isolation_command(command: &str, lock: bool, a_changed: bool, b_changed: bool) { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); - let b = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0); sel(&mut s, &[a, b]); let g = id_of(&s.execute("object.group", &json!({})).unwrap()); - let over = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0); let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[out]); + assert!(!find_command(command).unwrap().info(&s).enabled, "{command}: outside selection"); + sel(&mut s, &[a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + s.execute(command, &json!({})).unwrap(); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + assert_eq!(changed(&s, a), a_changed, "{command}: A"); + assert_eq!(changed(&s, b), b_changed, "{command}: B"); + assert!(!changed(&s, out) && !changed(&s, p) && !changed(&s, l2), "{command}: outside"); + assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: selection"); + let steps = usize::from(a_changed || b_changed); + assert_eq!(history(&s).0, before + steps, "{command}: history"); + if steps != 0 { + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!changed(&s, a) && !changed(&s, b), "{command}: undo"); + assert_eq!(selected(&s), [a], "{command}: undo selection"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((changed(&s, a), changed(&s, b)), (a_changed, b_changed), "{command}: redo"); + assert_eq!(selected(&s), if a_changed { vec![] } else { vec![a] }, "{command}: redo selection"); + } + if !a_changed && b_changed { + let restore = if lock { "object.unlockAll" } else { "object.showAll" }; + let params = if lock { json!({"id": out.0, "locked": true}) } else { json!({"id": out.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1})); + assert!(!changed(&s, b) && changed(&s, out), "{command}: scoped restore"); + } +} + +/// Generate the focused group isolation checks for each Lock and Hide command. +macro_rules! group_isolation_command_test { + ($name:ident, $command:literal, $lock:literal, $a:literal, $b:literal) => { + #[doc = concat!("Checks ", $command, " targets and history in group isolation.")] + #[test] + fn $name() { + check_group_isolation_command($command, $lock, $a, $b); + } + }; +} + +group_isolation_command_test!(lock_selection_in_group_isolation, "object.lock", true, true, false); +group_isolation_command_test!(lock_above_in_group_isolation, "object.lock.above", true, true, true); +group_isolation_command_test!(lock_other_layers_in_group_isolation, "object.lock.otherLayers", true, false, false); +group_isolation_command_test!(lock_unselected_in_group_isolation, "object.lock.unselected", true, false, true); +group_isolation_command_test!(hide_selection_in_group_isolation, "object.hide", false, true, false); +group_isolation_command_test!(hide_above_in_group_isolation, "object.hide.above", false, true, true); +group_isolation_command_test!(hide_other_layers_in_group_isolation, "object.hide.otherLayers", false, false, false); +group_isolation_command_test!(hide_unselected_in_group_isolation, "object.hide.unselected", false, false, true); + +/// Lock › Selection, Hide › Selection and All Artwork Above change only the selected path inside +/// an isolated compound path, with the other path below it. +#[test] +fn lock_and_hide_selection_in_isolated_compound_path() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let outside = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + sel(&mut s, &[hole]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null }; + assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}"); + assert_eq!(history(&s).0, before + 1, "{command}"); + assert_eq!(selected(&s), [], "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, hole), expected, "{command}"); + for id in [outer, compound, outside] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock › Selection, Hide › Selection and All Artwork Above change the whole compound path when +/// one of its paths is selected inside an isolated group that holds it. +#[test] +fn lock_and_hide_a_compound_path_member_in_an_isolated_group() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let b = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + sel(&mut s, &[compound, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[hole]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + s.execute(command, &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "{command}"); + assert_eq!(selected(&s), [], "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, compound), expected, "{command}"); + for id in [outer, hole, b, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Check that restore commands affect only isolated art and preserve undo and selection. +fn check_restore_in_group_isolation(change: &str, restore: &str, lock: bool) { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 20.0, 20.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let out = rect(&mut s, 30.0, 30.0, 100.0, 100.0); + let l2 = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + for id in [out, p] { + let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + } s.execute("object.isolate", &json!({"id": g.0})).unwrap(); sel(&mut s, &[a]); - off_in_isolation(&mut s, &["object.lock.above", "object.lock.otherLayers", "object.hide.above", "object.hide.otherLayers"]); - for id in [a, b, g, over, l2] { - assert_eq!(shown_and_locked(&s, id), (true, false), "{id:?}"); + s.execute(change, &json!({})).unwrap(); + assert!(selected(&s).is_empty()); + assert!(find_command(restore).unwrap().info(&s).enabled); + let before = history(&s).0; + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1})); + assert_eq!(history(&s).0, before + 1); + assert_eq!(selected(&s), [a]); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + assert!(!changed(&s, a) && !changed(&s, b)); + assert!(changed(&s, out) && changed(&s, p)); + let no_op = history(&s).0; + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 0})); + assert_eq!(history(&s).0, no_op); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(changed(&s, a)); + assert!(selected(&s).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!changed(&s, a) && changed(&s, out) && changed(&s, p) && !changed(&s, l2)); + assert_eq!(selected(&s), [a]); +} + +/// Unlock All restores locked art inside the group after Lock Selection clears selection. +#[test] +fn unlock_all_in_group_isolation_without_selection() { + check_restore_in_group_isolation("object.lock", "object.unlockAll", true); +} + +/// Show All restores hidden art inside the group after Hide Selection clears selection. +#[test] +fn show_all_in_group_isolation_without_selection() { + check_restore_in_group_isolation("object.hide", "object.showAll", false); +} + +/// With `scope: "group"`, Unlock All and Show All in an isolated compound path inside a group +/// change only the compound path's paths, not the group's other objects or a group outside it +/// that holds a selected object. +#[test] +fn group_scope_restore_stays_inside_isolated_compound_path() { + for (restore, lock) in [("object.unlockAll", true), ("object.showAll", false)] { + let mut s = session(); + let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hole = rect(&mut s, 20.0, 20.0, 20.0, 20.0); + sel(&mut s, &[outer, hole]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let sibling = rect(&mut s, 150.0, 0.0, 20.0, 20.0); + sel(&mut s, &[compound, sibling]); + s.execute("object.group", &json!({})).unwrap(); + let away = rect(&mut s, 300.0, 0.0, 20.0, 20.0); + let away_mate = rect(&mut s, 350.0, 0.0, 20.0, 20.0); + sel(&mut s, &[away, away_mate]); + s.execute("object.group", &json!({})).unwrap(); + for id in [hole, sibling, away_mate] { + let params = if lock { json!({"id": id.0, "locked": true}) } else { json!({"id": id.0, "visible": false}) }; + s.execute("layer.setProps", ¶ms).unwrap(); + } + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + let changed = |s: &Session, id| if lock { node(s, id).locked } else { !node(s, id).visible }; + sel(&mut s, &[away]); + assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 0}), "{restore}: outside selection"); + assert!(changed(&s, away_mate) && changed(&s, hole) && changed(&s, sibling), "{restore}: outside selection"); + sel(&mut s, &[outer]); + assert_eq!(s.execute(restore, &json!({"scope": "group"})).unwrap(), json!({"count": 1}), "{restore}"); + assert!(!changed(&s, hole), "{restore}: hole"); + assert!(changed(&s, sibling) && changed(&s, away_mate), "{restore}: outside"); + assert_eq!(selected(&s), [hole], "{restore}: selection"); + } +} + +/// Lock › Selection, Hide › Selection and All Artwork Above, with the isolated group and one of +/// its members both selected, change the member. +#[test] +fn lock_and_hide_with_the_isolated_group_selected_change_its_member() { + for command in ["object.lock", "object.hide", "object.lock.above", "object.hide.above"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[g, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + let before = history(&s).0; + let want = if command.ends_with(".above") { json!({"count": 1}) } else { serde_json::Value::Null }; + assert_eq!(s.execute(command, &json!({})).unwrap(), want, "{command}"); + assert_eq!(history(&s).0, before + 1, "{command}"); + let expected = if command.starts_with("object.lock") { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, a), expected, "{command}: A"); + for id in [b, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock and Hide Unselected with the isolated group and one of its members selected change only its other members. +#[test] +fn lock_and_hide_unselected_with_the_isolated_group_selected_keep_its_member() { + for command in ["object.lock.unselected", "object.hide.unselected"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + sel(&mut s, &[g, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 1}), "{command}"); + let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) }; + assert_eq!(shown_and_locked(&s, b), changed, "{command}: B"); + for id in [a, g] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + } +} + +/// Lock and Hide Unselected with the isolated layer and one of its objects selected change the layer's other objects, +/// and a selected sublayer inside the isolated layer keeps its art. +#[test] +fn lock_and_hide_unselected_with_the_isolated_layer_selected_keep_its_object() { + for command in ["object.lock.unselected", "object.hide.unselected"] { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let c = rect(&mut s, 400.0, 0.0, 100.0, 100.0); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + let changed = if command == "object.lock.unselected" { (true, true) } else { (false, false) }; + sel(&mut s, &[layer, a]); + assert!(find_command(command).unwrap().info(&s).enabled, "{command}"); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}"); + for id in [b, c] { + assert_eq!(shown_and_locked(&s, id), changed, "{command}: {id:?}"); + } + for id in [a, sub, layer] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: {id:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + sel(&mut s, &[layer, sub]); + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 2}), "{command}: sublayer"); + for id in [a, b] { + assert_eq!(shown_and_locked(&s, id), changed, "{command}: sublayer, {id:?}"); + } + for id in [c, sub, layer] { + assert_eq!(shown_and_locked(&s, id), (true, false), "{command}: sublayer, {id:?}"); + } + } +} + +/// Pattern editing keeps Lock Selection and Unlock All available for its tile art. +#[test] +fn pattern_editing_keeps_lock_and_unlock_available() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[a]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let tile = selected(&s)[0]; + assert!(find_command("object.lock").unwrap().info(&s).enabled); + s.execute("object.lock", &json!({})).unwrap(); + assert!(node(&s, tile).locked); + assert!(find_command("object.unlockAll").unwrap().info(&s).enabled); + s.execute("object.unlockAll", &json!({})).unwrap(); + assert!(!node(&s, tile).locked); + assert_eq!(selected(&s), [tile]); +} + +/// Opacity mask editing lets Lock and Hide Selection change mask art and restores it with Unlock All and Show All. +#[test] +fn opacity_mask_editing_keeps_lock_hide_and_restore_available() { + let mut s = session(); + let artwork = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + let mask_source = rect(&mut s, 0.0, 0.0, 100.0, 200.0); + sel(&mut s, &[artwork, mask_source]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("transparency.editOpacityMask", &json!({})).unwrap(); + let mask = selected(&s)[0]; + for (change, restore) in [("object.lock", "object.unlockAll"), ("object.hide", "object.showAll")] { + assert!(find_command(change).unwrap().info(&s).enabled, "{change}"); + s.execute(change, &json!({})).unwrap(); + assert!(selected(&s).is_empty(), "{change}"); + assert_eq!(shown_and_locked(&s, mask), if change == "object.lock" { (true, true) } else { (false, false) }); + assert!(find_command(restore).unwrap().info(&s).enabled, "{restore}"); + assert_eq!(s.execute(restore, &json!({})).unwrap(), json!({"count": 1}), "{restore}"); + assert_eq!(shown_and_locked(&s, mask), (true, false), "{restore}"); + assert_eq!(selected(&s), [mask], "{restore}"); + } +} + +/// Other Layers changes nothing in an isolated layer or sublayer. +#[test] +fn other_layers_has_no_target_in_isolated_layers_or_sublayers() { + for sublayer in [false, true] { + let mut s = session(); + let layer = s.doc().unwrap().doc.layers[0].id; + let root = if sublayer { id_of(&s.execute("layer.newSublayer", &json!({"parent": layer.0})).unwrap()) } else { layer }; + s.execute("layer.setCurrent", &json!({"id": root.0})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let other = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + s.execute("object.isolate", &json!({"id": root.0})).unwrap(); + sel(&mut s, &[a]); + for command in ["object.lock.otherLayers", "object.hide.otherLayers"] { + assert!(find_command(command).unwrap().info(&s).enabled); + let before = history(&s).0; + assert_eq!(s.execute(command, &json!({})).unwrap(), json!({"count": 0})); + assert_eq!(history(&s).0, before); + assert_eq!(selected(&s), [a]); + assert_eq!(shown_and_locked(&s, other), (true, false)); + } } - s.execute("object.exitIsolation", &json!({})).unwrap(); - sel(&mut s, &[g]); - assert_eq!(s.execute("object.lock.above", &json!({})).unwrap(), json!({"count": 1})); - s.execute("object.hide.otherLayers", &json!({})).unwrap(); - assert_eq!(shown_and_locked(&s, over), (true, true)); - assert_eq!(shown_and_locked(&s, l2), (false, false)); } /// How many steps there are to undo and to redo, and whether the document has unsaved changes. @@ -580,12 +790,10 @@ fn hide_unselected_artwork_leaves_the_art_on_a_locked_artboard() { assert_eq!([a, b, on_locked].map(|id| node(&s, id).visible), [true, false, true]); } -/// In isolation mode Hide › Unselected Artwork is disabled: the menu item is off, and the command returns an error that -/// names isolation mode and changes nothing. While Lock Guides is on it leaves the guides as they are. With nothing -/// left to hide it records no undo step and returns a count of 0. A compound path that holds a selected path stays as -/// it is. +/// Hide Unselected affects only isolated art, keeps locked guides, records no step for a no-op, and +/// preserves a compound path that holds the selected path. #[test] -fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode() { +fn hide_unselected_artwork_keeps_locked_guides_and_scopes_isolation() { let mut s = session(); let guide = rect(&mut s, 0.0, 0.0, 10.0, 10.0); sel(&mut s, &[guide]); @@ -600,17 +808,15 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::>(); s.execute("object.isolate", &json!({"id": g.0})).unwrap(); select_with_a_step_to_redo(&mut s, &[m]); - let before = history(&s); - let info = find_command("object.hide.unselected").unwrap().info(&s); - assert!(!info.enabled && info.disabled_reason.as_deref() == Some("exit isolation mode first"), "{info:?}"); - let e = s.execute("object.hide.unselected", &json!({})).unwrap_err(); - assert!(matches!(e, EngineError::Disabled(..)) && e.to_string().contains("isolation mode"), "{e}"); - assert_eq!(shown(&s, &[m, n, out, guide]), [true; 4]); - assert_eq!((history(&s), selected(&s)), (before, vec![m])); + let before = history(&s).0; + assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled); + assert_eq!(hide(&mut s), json!({"count": 1})); + assert_eq!(history(&s).0, before + 1); + assert_eq!(shown(&s, &[m, n, out, guide]), [true, false, true, true]); + assert_eq!(selected(&s), [m]); s.execute("object.exitIsolation", &json!({})).unwrap(); sel(&mut s, &[m]); - assert!(find_command("object.hide.unselected").unwrap().info(&s).enabled); - assert_eq!(hide(&mut s), json!({"count": 2})); + assert_eq!(hide(&mut s), json!({"count": 1})); assert_eq!(shown(&s, &[n, out, guide]), [false, false, true]); select_with_a_step_to_redo(&mut s, &[m]); let before = history(&s); @@ -621,7 +827,7 @@ fn hide_unselected_artwork_keeps_locked_guides_and_is_disabled_in_isolation_mode sel(&mut s, &[m]); assert_eq!(hide(&mut s), json!({"count": 1})); assert_eq!(shown(&s, &[guide]), [false]); - // A compound path that holds the selected path stays as it is with its paths. + // The compound path and its paths stay visible when one path is selected. let outer = rect(&mut s, 0.0, 200.0, 100.0, 100.0); let hole = rect(&mut s, 40.0, 240.0, 20.0, 20.0); sel(&mut s, &[outer, hole]); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index be98613162..025cf6d30a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2,7 +2,7 @@ //! on-path type from paths, Fit Headline, Convert To Area/Point Type. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind, TextKind, TextObject}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextKind, TextObject}; use vectorcraft_geom::Point; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; @@ -87,6 +87,168 @@ fn set_range_style_splits_runs() { assert!(s.execute("text.setRangeStyle", &json!({"id": id.0, "size": -1})).is_err()); } +#[test] +fn optical_command_manual_pair_undo_redo_and_native_reopen() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 70})).unwrap(); + let result = s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + assert_eq!(result["kerning"], "optical"); + assert!(obj(&s, id).runs[0].style.optical_kerning); + assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0)); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "kerning": 0})).unwrap(); + let styled = obj(&s, id); + assert_eq!(styled.runs.iter().map(|r| r.style.kerning).collect::>(), vec![Some(70.0), Some(0.0), Some(70.0)]); + assert!(styled.runs.iter().all(|r| r.style.optical_kerning)); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let opened = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(reopened) = &opened.node(id).unwrap().kind else { panic!("text missing") }; + assert_eq!( + reopened.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::>(), + styled.runs.iter().map(|r| (r.style.optical_kerning, r.style.kerning)).collect::>() + ); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.kerning, Some(70.0)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(obj(&s, id).runs[1].style.kerning, Some(0.0)); + assert!(obj(&s, id).runs.iter().all(|r| r.style.optical_kerning)); +} + +#[test] +fn optical_set_format_keeps_existing_pair_override() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 40})).unwrap(); + let result = s.execute("text.setFormat", &json!({"ids": [id.0], "kerning": "optical"})).unwrap(); + assert_eq!(result["kerning"], "optical"); + let t = obj(&s, id); + assert!(t.runs.iter().all(|r| r.style.optical_kerning)); + assert_eq!(t.runs[0].style.kerning, Some(40.0)); +} + +#[test] +fn optical_kerning_step_starts_from_the_automatic_pair() { + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AVA", "size": 100, "font": "JetBrains Mono"})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + let t = obj(&s, id); + let optical = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let mut manual = t.clone(); + vectorcraft_text::edit::style_range(&mut manual.runs, 0, 1, |st| st.kerning = Some(0.0)); + let unkerned = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &manual); + let auto = (optical.glyphs[0].advance - unkerned.glyphs[0].advance) * 1000.0 / 100.0; + assert!(auto.abs() > 1.0, "the font needs a measurable shape correction"); + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() - auto - s.prefs.tracking_increment).abs() < 0.01); + assert!(after.runs.iter().all(|r| r.style.optical_kerning)); +} + +#[test] +fn metrics_pair_step_preserves_the_drawn_auto_position() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let mut s = session(); + let id = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "AV", "size": 100, "font": PAIR_KERNING_FAMILY})).unwrap()["id"].as_u64().unwrap(), + ); + let before = obj(&s, id); + let auto = vectorcraft_text::layout(db, &before); + let drawn_v = |layout: &vectorcraft_text::TextLayout| layout.glyphs.iter().find(|g| g.byte == 1).unwrap().xf.as_coeffs()[4]; + assert!((crate::cmd::effective_kerning(db, &before, &auto, 0, 1) + 160.0).abs() < 0.01); + let mut same = before.clone(); + vectorcraft_text::edit::style_range(&mut same.runs, 0, 1, |st| st.kerning = Some(-160.0)); + assert!((drawn_v(&vectorcraft_text::layout(db, &same)) - drawn_v(&auto)).abs() < 0.01); + + s.execute("type.step", &json!({"id": id.0, "start": 1, "end": 1, "attribute": "kerning", "by": 1})).unwrap(); + let after = obj(&s, id); + assert!((after.runs[0].style.kerning.unwrap() + 160.0 - s.prefs.tracking_increment).abs() < 0.01); + let moved = drawn_v(&vectorcraft_text::layout(db, &after)) - drawn_v(&auto); + assert!((moved - s.prefs.tracking_increment * 0.1).abs() < 0.01, "V moves by one kerning increment: {moved}"); +} + +#[test] +fn effective_auto_kerning_at_area_line_end_survives_unkerned_wrap() { + use vectorcraft_text::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + + let db = vectorcraft_text::FontDb::global(); + db.add_font(pair_kerning_font().unwrap()); + let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AV", style); + let mut wrapping_pair = None; + for width in 80..160 { + text.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(width), 300.0)) }; + let auto = vectorcraft_text::layout(db, &text); + let mut trial = text.clone(); + vectorcraft_text::edit::style_range(&mut trial.runs, 0, 1, |st| st.kerning = Some(0.0)); + let unkerned = vectorcraft_text::layout(db, &trial); + if auto.glyphs.len() >= 2 + && unkerned.glyphs.len() >= 2 + && auto.glyphs[0].line == auto.glyphs[1].line + && unkerned.glyphs[0].line != unkerned.glyphs[1].line + { + wrapping_pair = Some((text.clone(), auto, unkerned)); + break; + } + } + let (text, auto, unkerned) = wrapping_pair.expect("the kerned pair fits on a line that wraps the unkerned pair"); + assert_ne!(unkerned.glyphs[0].line, unkerned.glyphs[1].line); + assert!((crate::cmd::effective_kerning(db, &text, &auto, 0, 1) + 160.0).abs() < 0.01); +} + +#[test] +fn effective_optical_kerning_reads_the_right_to_left_pair() { + use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1); + let style = CharStyle { font_family: RIGHT_TO_LEFT_OPTICAL_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let text = TextObject::point(Point::ZERO, "אב", style); + let optical = vectorcraft_text::layout(&db, &text); + let mut manual = text.clone(); + manual.runs[0].style.kerning = Some(0.0); + let unkerned = vectorcraft_text::layout(&db, &manual); + let drawn_gap = |lay: &vectorcraft_text::TextLayout| { + let drawn = |byte| lay.glyphs.iter().find(|g| g.byte == byte).unwrap().xf.as_coeffs()[4]; + drawn(2) - drawn(0) + }; + let expected = (drawn_gap(&optical) - drawn_gap(&unkerned)) * 10.0; + assert!(expected.abs() > 1.0, "the outlined pair has a measurable Optical correction"); + let actual = crate::cmd::effective_kerning(&db, &text, &optical, 0, 2); + assert!((actual - expected).abs() < 0.01, "the caret reads the adjacent right-to-left pair"); +} + +#[test] +fn reset_tracking_clears_manual_pairs_without_changing_optical_mode() { + let mut s = session(); + let id = text(&mut s, "III"); + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": "optical"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 1, "kerning": 80})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let (a, b) = vectorcraft_text::caret_position(&lay, 1); + let p = t.xf * a.midpoint(b); + click(&mut s, p.x, p.y); + assert!(s.tool_wants_text()); + s.set_tool_option("select", &json!({"start": 1, "end": 1})); + s.execute("type.resetTracking", &json!({})).unwrap(); + let caret = obj(&s, id); + assert_eq!(caret.runs[0].style.kerning, None); + assert!(caret.runs.iter().all(|r| r.style.optical_kerning)); + + s.execute("text.setRangeStyle", &json!({"id": id.0, "kerning": 60, "tracking": 30})).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 3})); + s.execute("type.resetTracking", &json!({})).unwrap(); + let range = obj(&s, id); + assert!(range.runs.iter().all(|r| r.style.kerning.is_none() && r.style.tracking == 0.0)); + assert!(range.runs.iter().all(|r| r.style.optical_kerning)); +} + /// A character style applied from byte 2^32 to 2^32 + 5 styles no character, as a range past the /// end does. A 32-bit build read the range as bytes 0 to 5 and styled "Hello". #[test] diff --git a/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 b/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 new file mode 100644 index 0000000000..60f2c24239 Binary files /dev/null and b/crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2 differ diff --git a/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k b/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k new file mode 100644 index 0000000000..0e2196656b Binary files /dev/null and b/crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k differ diff --git a/crates/engine/tests/fixtures/jpeg2000/checker.jp2 b/crates/engine/tests/fixtures/jpeg2000/checker.jp2 new file mode 100644 index 0000000000..787ca865d8 Binary files /dev/null and b/crates/engine/tests/fixtures/jpeg2000/checker.jp2 differ diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 0f096b62ad..10109e1ec3 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1781,6 +1781,31 @@ proptest! { // ---------- SVG saved with hidden layers and editing data ---------- +proptest! { + #![proptest_config(config())] + + /// Mutated JP2 boxes and raw codestream markers must return errors rather than unwind. + #[test] + fn mutated_jpeg2000_files_do_not_panic(raw in any::(), cut in 0usize..300, edits in prop::collection::vec((0usize..300, any::()), 0..8)) { + let (name, mut bytes) = if raw { + ("a.j2k", include_bytes!("fixtures/jpeg2000/checker-raw.j2k").to_vec()) + } else { + ("a.jp2", include_bytes!("fixtures/jpeg2000/checker.jp2").to_vec()) + }; + for (at, byte) in edits { + if let Some(slot) = bytes.get_mut(at) { *slot = byte; } + } + bytes.truncate(cut); + let result = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let params = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", ¶ms)); + let _ = no_panic(s.execute("file.place", ¶ms)); + }); + prop_assert!(result.is_ok(), "{name}: panicked: {:?}", result.err()); + } +} + /// The rich document with a hidden layer, saved as SVG with its editing data. fn saved_svg() -> String { let mut d = rich_doc(); @@ -2784,9 +2809,126 @@ fn text_eps_of(document: &str, objects: &str) -> Vec { editing_eps(&editing) } +/// A text document of `kinds.len()` stories, story `i` in frame `i` of kind `kinds[i]` (0 point type, +/// 1 area type, 2 type on a path, others a kind the reader doesn't know), with a line break inside +/// its paragraph (`\x03`) at each of `soft` (by character, wrapping, the story's end included) and +/// its paragraph runs `runs` characters long (the whole story when there are none). +fn stories_document_text(kinds: &[u8], soft: &[usize], runs: &[usize]) -> String { + let frames: Vec = kinds + .iter() + .enumerate() + .map(|(i, kind)| { + // Six rows 15 apart on the page (the canvas is y down), then the same rows again a little + // to the right. + let (x, y) = (8150.0 + (i / 6) as f64 * 5.0, 8150.0 + (i % 6) as f64 * 15.0); + match kind { + 0 => format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + 1 => format!( + "<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} {0} {y} {0} {y} {0} {1} {0} {1} {0} {1} {0} {1} {x} {1} {x} {1} ] >> /2 << /0 1 >> >> >>", + x + 70.0, + y + 12.0 + ), + 2 => format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} ] >> /2 << /0 2 /6 [ 0 0.9 ] >> >> >>", x + 70.0), + k => format!("<< /0 << /0 [ 0 0 ] /2 << /0 {k} /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + } + }) + .collect(); + let stories: Vec = (0..kinds.len()) + .map(|i| { + let mut chars: Vec = format!("Line {i} one two\rand three\r").chars().collect(); + for at in soft { + chars.insert(at % (chars.len() + 1), '\x03'); + } + let n = chars.len(); + let text: String = chars.iter().map(|c| match c { + '\r' => "\\r".to_string(), + '\x03' => "\\003".to_string(), + c => c.to_string(), + }).collect(); + let lengths: Vec = if runs.is_empty() { vec![n] } else { runs.to_vec() }; + let paras: String = lengths + .iter() + .enumerate() + .map(|(j, len)| format!("<< /0 << /0 << /0 () /5 << /0 {} /2 2 /4 {j} >> /6 0 >> >> /1 {len} >> ", j % 3)) + .collect(); + format!( + "<< /0 << /0 ({text}) /5 << /0 [ {paras}] >> /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 8.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 {i} >> ] >> >>" + ) + }) + .collect(); + format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} ] >> >>\n/1 << /1 [ {} ] /2 << /1 12.0 >> >>\n", + frames.join(" "), + stories.join(" ") + ) +} + +/// An EPS whose page draws `page` (PostScript), with the text `objects` on a layer that shows and +/// the stories in `document`. +fn shown_text_eps(document: &str, objects: &str, page: &str) -> Vec { + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let editing = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Words) Ln\n{objects}LB\n%AI5_EndLayer--\n\ + %AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + lines.join("\n") + ); + let stream = ascii85(&zstd(&editing)); + let private: Vec = stream.as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont {page}\nshowpage\n%%EOF\n%AI9_PrivateDataBegin\n%AI24_DataStream\n{}\n%AI9_PrivateDataEnd\n", + private.join("\n") + ) + .into_bytes() +} + +/// The page of [`stories_document_text`]'s first story's first line, at its place. +const FIRST_LINE: &str = "8.5 91.5 moveto (Line 0 one two) show"; + +/// The text objects of `pairs` (story, frame among the story's). +fn story_objects(pairs: &[(u32, u32)]) -> String { + pairs.iter().map(|(story, frame)| format!("/AI11Text :\n{frame} /FrameIndex ,\n{story} /StoryIndex ,\n;\n")).collect() +} + +/// The fixture, as it is (point type, area type and type on a path, a line break inside each +/// paragraph), opens with its layers and every story's type from its text document. +#[test] +fn the_shown_stories_fixture_opens_with_its_layers() { + let doc = stories_document_text(&[0, 1, 2], &[4], &[]); + // Each story's first line where the page draws it: the area type's below its frame's top, the + // type on a path on its path. + let page = format!("{FIRST_LINE} 8.5 69.5 moveto (Line 1) show 8.5 61.5 moveto (Line 2) show"); + let l = vectorcraft_engine::cmd::fileio::load("x.eps", &shown_text_eps(&doc, &story_objects(&[(0, 0), (1, 0), (2, 0)]), &page)).unwrap(); + let names: Vec<_> = l.doc.layers.iter().map(|l| l.name.clone()).collect(); + assert_eq!(names, [Some("Words".to_string())], "{:?}", l.warnings); + let mut texts = vec![]; + l.doc.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + assert_eq!(texts.len(), 3, "{texts:?} {:?}", l.warnings); + assert!(texts.iter().all(|t| t.contains('\u{2028}') && t.contains('\n')), "{texts:?}"); +} + proptest! { #![proptest_config(config())] + /// An Illustrator EPS with text objects that show, in frames of every kind and some the reader + /// doesn't know, naming stories and frames that may not exist, with line breaks inside their + /// paragraphs and paragraph runs of any length: read as its layers, or as its page. + #[test] + fn eps_shown_stories_never_panic( + kinds in prop::collection::vec(0u8..4, 1..20), + pairs in prop::collection::vec((0u32..24, 0u32..3), 1..24), + soft in prop::collection::vec(0usize..40, 0..5), + runs in prop::collection::vec(0usize..40, 0..5), + ) { + let kinds: Vec = kinds.into_iter().map(|k| if k == 3 { 9 } else { k }).collect(); + let bytes = shown_text_eps(&stories_document_text(&kinds, &soft, &runs), &story_objects(&pairs), FIRST_LINE); + survive("EPS with shown stories", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + } + /// An Illustrator EPS whose text document is damaged or hostile: read as its type, or without it. #[test] fn eps_text_document_never_panics(cut in 0usize..1_500, edits in prop::collection::vec((0usize..1_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1'])), 0..12)) { diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 6ad647cad3..60273bb508 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -8,9 +8,9 @@ //! The format isn't documented. What is read here was worked out from the files of the project's //! users, used locally and never committed, by comparing it with the type their pages draw: the //! meaning of each key below was checked against the page's own type in more than a thousand text -//! objects, and it is only used for the keys that matched. A story the reader doesn't recognise (area -//! type, type on a path, anything with a frame that has more than a point and a matrix) is left -//! alone: it has no text, and the importer says so. +//! objects, and it is only used for the keys that matched. Point type, area type and type on a path +//! are read; a story in a frame of any other kind is left alone: it has no text, and the importer +//! says so. //! //! Where type sits: a story lays its lines out round a point `F` (the anchor: the start of a line of //! left-aligned type, the middle of a centred one, the end of a right-aligned one), each line with an @@ -654,11 +654,6 @@ impl Story { self.text.len() } - /// The story's characters, with `\r` ending paragraphs and `\x03` ending lines. - pub(super) fn text(&self) -> &str { - &self.text - } - /// The point frame's matrix (the first frame's, when it is one), else the identity. fn matrix(&self) -> [f64; 6] { match self.frames.first() { @@ -749,10 +744,20 @@ impl Story { (1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end }) } }; + // A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the + // paragraph's style runs over. let text: String = if threaded { String::new() } else { - self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect() + self.text + .trim_end_matches('\r') + .chars() + .map(|c| match c { + '\r' => '\n', + '\x03' => '\u{2028}', + c => c, + }) + .collect() }; if text.trim().is_empty() && !threaded { return None; @@ -1253,6 +1258,21 @@ mod tests { assert_eq!(story("one\r", &[0.0], &Para::default()).line_leading(1.0), None); } + /// A `\x03` ends a line inside its paragraph: it comes in as a forced line break, and the + /// paragraph's style runs over it to the paragraph's end. + #[test] + fn a_soft_return_is_a_line_break_in_its_paragraph() { + let para = Para { space_before: 4.0, space_after: 2.0, first_indent: 6.0, ..Para::default() }; + let mut s = story("A\x03B\rC\r", &[0.0, 15.6, 31.2], ¶); + s.paras[1].1 = Para { left_indent: 3.0, ..para.clone() }; + let node = s.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let NodeKind::Text(t) = &node.kind else { panic!("not text") }; + assert_eq!(t.plain_text(), "A\u{2028}B\nC"); + assert_eq!(t.paras.len(), 2, "{:?}", t.paras); + assert_eq!((t.paras[0].first_line_indent, t.paras[0].left_indent, t.paras[0].space_before), (6.0, 0.0, 4.0)); + assert_eq!((t.paras[1].first_line_indent, t.paras[1].left_indent), (6.0, 3.0)); + } + #[test] fn a_frame_too_short_for_its_first_line_is_made_taller() { // A heading in a frame as tall as its size: a line of the font it shows in here is taller. diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 42f968faa5..efbb8a3a11 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -12,10 +12,12 @@ //! colours, gradients, transparency and images of the art. //! //! Text objects are slots in that document: their characters, fonts and places are in the file's -//! text document (see `ate`). Type that shows comes from the page, which draws it, into the slot -//! whose text is where the page has it. Type that doesn't show (a hidden layer or object, or off -//! the page) is made from the text document; where that can't be read (area type, type on a path) -//! it's left out, with a warning. +//! text document (see `ate`). When the text document has the type of every text object that shows, +//! all the type is made from it, each text object in its own place, and the page's type is only +//! compared with it. Otherwise the type it has is still made from it, and the page's type that +//! lies elsewhere goes into the text objects it can't make, by where the text document puts their +//! lines or else in painting order. A text object whose type neither has (a frame of a kind it +//! doesn't read, on a hidden layer or object) is left out, with a warning. //! //! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is @@ -46,7 +48,9 @@ mod slots; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; #[cfg(test)] -use compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour}; +use compare::{ + MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, +}; pub use layers::{ai_alone, layered_ai}; pub(super) use layers::{layered, program_alone}; pub use slots::is_loss; @@ -88,7 +92,7 @@ mod tests { let rect = page.artboards[0].rect; let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; let mut view = PageView::new(&frame); - assert_eq!(prune_unseen(&frame, &mut view, &mut layers), 1, "only the ring the page doesn't draw"); + assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw"); let widths: Vec = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); assert_eq!(widths, [12.0, 6.0]); // Taken by lightness alone, the red and the dark red are alike. @@ -99,6 +103,33 @@ mod tests { assert!(!differ(&px(dark), &px(red)) && differ_in_colour(&px(dark), &px(red))); } + /// The share of a rectangle's pixels in the areas, however many areas there are: none for one + /// that only shares their edge, lies off the drawing or isn't a number. + #[test] + fn the_share_of_a_rectangle_in_the_areas_counts_its_pixels() { + let in_areas = |areas: &[Rect], w: usize, h: usize| { + let marks: Vec = (0..w * h) + .map(|k| { + let (x, y) = ((k % w) as f64 + 0.5, (k / w) as f64 + 0.5); + areas.iter().any(|a| a.contains(Point::new(x, y))) + }) + .collect(); + let shares = Shares::of(&marks, w, h); + move |r: &Rect| shares.share(r) + }; + let share = in_areas(&[Rect::new(10.0, 10.0, 20.0, 20.0), Rect::new(30.0, 0.0, 31.0, 1.0)], 40, 40); + assert_eq!((share(&Rect::new(12.0, 12.0, 22.0, 18.0)), share(&Rect::new(10.0, 10.0, 30.0, 20.0))), (0.8, 0.5)); + assert_eq!((share(&Rect::new(15.0, 15.0, 30.0, 30.0)), share(&Rect::new(30.2, 0.2, 30.8, 0.8))), (25.0 / 225.0, 1.0)); + assert_eq!( + [share(&Rect::new(20.0, 20.0, 30.0, 30.0)), share(&Rect::new(0.0, 0.0, 5.0, 5.0)), share(&Rect::new(50.0, 50.0, 60.0, 60.0))], + [0.0; 3] + ); + assert_eq!(share(&Rect::new(f64::NAN, 0.0, 39.0, 39.0)), 0.0); + let many: Vec = (0..5000).map(|i| Rect::new(f64::from(i % 70), 50.0, f64::from(i % 70) + 1.0, 51.0)).collect(); + let share = in_areas(&many, 80, 80); + assert_eq!((share(&Rect::new(60.0, 50.0, 75.0, 51.0)), share(&Rect::new(70.0, 50.0, 75.0, 51.0))), (10.0 / 15.0, 0.0)); + } + fn piece(text: &str, x: f64, y: f64) -> Arc { Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(x, y), text, CharStyle::default()))))) } @@ -163,9 +194,9 @@ mod tests { assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page"); let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; let mut view = PageView::new(&frame); - assert!(compare(&frame, &mut view, &vector).is_ok()); - assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0)).is_err(), "missing artwork remains an error"); + assert!(compare(&frame, &mut view, &vector, false).is_ok()); + assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error"); let shifted = Rect::new(0.0, 0.0, 500.0, 500.0); - assert!(view.difference(&vector, shifted).any > MAX_DIFFERENCE, "wrong framing remains an error"); + assert!(view.difference(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error"); } } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 8e80703d76..1dd8b7d2b0 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,8 +1,8 @@ use super::compare::{MAX_DIFFERENCE, PageView, compare, difference}; -use super::plan::plan; +use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, - letters, text_objects, words, + ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, + fill_slots, letters, text_objects, words, }; use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai}; @@ -183,10 +183,6 @@ pub(super) fn build_from( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - // The page's type is compared with every text object of the layers: that has its limits. - if infos.len() > MAX_SLOTS || infos.len().saturating_mul(shown.len()) > MAX_PAIRS { - return Err("it has too many text objects".into()); - } let texts = Texts::read(data); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); @@ -202,7 +198,8 @@ pub(super) fn build_from( } let template = template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); let mut notes = warnings; - let content = plan(&infos, &stories, template, to_doc, [&shown, &hidden], &mut notes); + let own = (!outlined).then(|| outside_placed_files(&shown, &doc, &placed_elsewhere)); + let (content, reflow) = slot_content(&infos, &stories, template, to_doc, own.as_deref(), [&shown, &hidden], &mut notes)?; // The glyphs left out with the rest of the page's art, and how many text objects take type of // the page right next to them (not counted past `MAX_PAIRS` comparisons). let compared = lone.len().saturating_mul(shown.iter().chain(&hidden).map(Vec::len).sum()); @@ -211,7 +208,7 @@ pub(super) fn build_from( matches!(n.kind, NodeKind::Text(_)) && n.visual_bounds().is_some_and(|b| missing.iter().any(|r| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).is_zero_area())) }; - let short = content.iter().filter(|c| matches!(c, Content::Page(p) | Content::Made(_, _, _, p) if p.iter().any(next_to_missing))).count(); + let short = content.iter().filter(|c| matches!(c, Content::Page(p) if p.iter().any(next_to_missing))).count(); let mut empty = 0; let mut layers = std::mem::take(&mut doc.layers); let mut made = vec![]; @@ -244,16 +241,16 @@ pub(super) fn build_from( // doesn't draw is weighed again with the images there, since an image that covered a // text object at the first placement may not cover it at the other. let other = elsewhere(&doc, &placed_elsewhere); - let unseen = prune_unseen(&frame, &mut view, &mut doc); + let unseen = prune_unseen(&frame, &mut view, &mut doc, reflow); let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); - match compare(&frame, &mut view, &doc) { + match compare(&frame, &mut view, &doc, reflow) { // Placed files at the other point their data gives, where that draws closer to the // page: a small image in the wrong place differs too little to fail. Ok(note) => { let closer = other.and_then(|mut other| { - let unseen = prune_unseen(&frame, &mut view, &mut other); - let closer = view.difference(&other, frame.rect).any < view.difference(&doc, frame.rect).any; - closer.then(|| compare(&frame, &mut view, &other).ok()).flatten().map(|note| (other, unseen, note)) + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + let closer = view.difference(&other, frame.rect, reflow).any < view.difference(&doc, frame.rect, reflow).any; + closer.then(|| compare(&frame, &mut view, &other, reflow).ok()).flatten().map(|note| (other, unseen, note)) }); match closer { Some((other, unseen, note)) => { @@ -265,8 +262,8 @@ pub(super) fn build_from( } // Placed files at the other point their data gives, where that draws as the page. Err(why) => match other.map(|mut other| { - let unseen = prune_unseen(&frame, &mut view, &mut other); - (compare(&frame, &mut view, &other), other, unseen) + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + (compare(&frame, &mut view, &other, reflow), other, unseen) }) { Some((Ok(note), other, unseen)) => { doc = other; @@ -288,6 +285,34 @@ pub(super) fn build_from( Ok((doc, notes)) } +/// What goes into each of `infos`' slots, and whether the type is all made from the file's text +/// document. When the text document makes the type of every text object that shows (and the type +/// isn't asked for as outlines: `own` has the page's text objects that show outside placed files), +/// each slot takes its own made type and the page's type is only compared with it: type laid out +/// again, in another font where the file's isn't installed, may differ from the page's. Otherwise +/// see [`plan`], with `pages` (the page's text objects that show and that don't). +fn slot_content( + infos: &[SlotInfo], + stories: &[Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + own: Option<&[Vec>]>, + pages: [&[Vec>]; 2], + notes: &mut Vec, +) -> Result<(Vec, bool), String> { + let made = make_slots(infos, stories, template, to_doc, notes); + if let Some(own) = own.filter(|_| readable_all(infos, &made)) { + return Ok((made_only(infos, made, [own, pages[1]], notes), true)); + } + // The page's type is matched with every text object whose type isn't made, and weighed against + // where every made one draws: that has its limits. + let open = made.iter().filter(|m| m.is_none()).count(); + if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + return Err("it has too many text objects".into()); + } + Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) +} + /// `doc` with the placed files `placed` lists at their other placement (see /// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when /// none is listed. @@ -391,6 +416,21 @@ fn in_placed_files(objects: &[Vec>], doc: &Document, placed: &[(NodeId inside(doc) || elsewhere(doc, placed).is_some_and(|other| inside(&other)) } +/// The page's text objects in `objects` that don't lie inside a placed file that shows in `doc`, at +/// either placement (see [`in_placed_files`]): the placed file's preview has the others. +fn outside_placed_files(objects: &[Vec>], doc: &Document, placed: &[(NodeId, Affine)]) -> Vec>> { + let mut files = vec![]; + placed_files(&doc.layers, &mut files); + if let Some(other) = elsewhere(doc, placed) { + placed_files(&other.layers, &mut files); + } + if files.is_empty() { + return objects.to_vec(); + } + let inside = |o: &[Arc]| extent(o).is_some_and(|r| files.iter().any(|f| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r))); + objects.iter().filter(|o| !inside(o)).cloned().collect() +} + /// Where the placed files that show in `nodes` are: the linked images the editing data's reader /// makes of them. fn placed_files(nodes: &[Arc], out: &mut Vec) { @@ -520,15 +560,16 @@ fn take_out(nodes: &mut Vec>, id: NodeId, hide: bool) -> bool { /// The text objects made from the file's text document that show and print on the page's area, /// where the page has no type to match them, and that the layers look no worse without, are not /// drawn by the app that wrote the file (which paints every shown text object; it keeps the type -/// of what was turned to outlines): they are taken out. How many. -pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> usize { +/// of what was turned to outlines): they are taken out. How many. `reflow`: the type is all laid +/// out again from the text document (see [`compare`]). +pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, reflow: bool) -> usize { let mut found = vec![]; unmark(&mut doc.layers, true, true, &mut found); let rect = frame.rect; if found.is_empty() || found.len() > MAX_WEIGHED { return 0; } - let with = view.difference(doc, rect).any; + let with = view.difference(doc, rect, reflow).weighed(reflow); // Taking a text object out changes only what is drawn in its box. When the art would still // differ from the page by more than `compare` allows with every candidate gone, the layers // aren't used whatever is pruned: don't draw them again for each one (#758). diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index cf86445e59..e8ebed707f 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -75,6 +75,14 @@ pub(super) struct Difference { pub(super) solid: f64, } +impl Difference { + /// The share [`compare`] holds to [`MAX_DIFFERENCE`]: every pixel that differs, or with `reflow` + /// (type laid out again from the file's text) those away from type. + pub(super) fn weighed(&self, reflow: bool) -> f64 { + if reflow { self.art } else { self.any } + } +} + /// The scale the comparisons draw a region at: about 400 pixels along its longer side. fn compare_scale(r: Rect) -> f64 { (400.0 / r.width().max(r.height()).max(1.0)).min(4.0) @@ -129,6 +137,8 @@ pub(super) struct PageView { /// rendering of the style there, the layers VectorCraft's live effects, and the two aren't /// held to look alike. restyled: Vec, + /// Where the page draws anything (its type, or its own outlines of type) or has its type. + page_marks: Shares, layers: vectorcraft_render::Renderer, scale: f64, samples: u32, @@ -144,7 +154,11 @@ impl PageView { let page = comparison_render(&mut vectorcraft_render::Renderer::new(), frame.page, ra, scale, samples); let mut page_type = vec![]; type_areas(&frame.page.layers, ra, scale, &mut page_type); - Self { page, page_type, restyled: vec![], layers: vectorcraft_render::Renderer::new(), scale, samples } + let (w, h) = (page.width as usize, page.height as usize); + let typed = in_areas(&page_type, w, h); + let marks: Vec = page.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || ink(on_white(p)) > WHITE).collect(); + let page_marks = Shares::of(&marks, w, h); + Self { page, page_type, restyled: vec![], page_marks, layers: vectorcraft_render::Renderer::new(), scale, samples } } /// Leave the drawn looks in `looks` (on `region`, the page's area in the layers' document) out @@ -159,13 +173,27 @@ impl PageView { } /// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]). - pub(super) fn difference(&mut self, b: &Document, rb: Rect) -> Difference { + /// With `reflow` (`b`'s type laid out again from the file's text), type counts as type only where + /// both have something: `b`'s where the page has type or draws anything in at least [`MARKED`] + /// of it, the page's where at least half of it lies where `b` has a text object, shown or not, + /// or a placed file. Elsewhere it is art the other lacks. + pub(super) fn difference(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { // The page doesn't print what isn't printed. let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - let mut areas = self.page_type.clone(); + let mut areas = vec![]; type_areas(&b.layers, rb, self.scale, &mut areas); + if reflow { + areas.retain(|r| self.page_marks.share(r) >= MARKED); + let mut texts = vec![]; + all_type_areas(&b.layers, rb, self.scale, &mut texts); + let (w, h) = (self.page.width as usize, self.page.height as usize); + let on_layers = Shares::of(&in_areas(&texts, w, h), w, h); + areas.extend(self.page_type.iter().filter(|r| on_layers.share(r) >= 0.5)); + } else { + areas.extend(&self.page_type); + } compared(&self.page, &y, &areas, &self.restyled) } @@ -241,6 +269,62 @@ fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec } } +/// Where every text object in `nodes` is, shown or not, as [`type_areas`] gives it, and every placed +/// file (whose preview draws the type it has). +fn all_type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { + for n in nodes { + let placed = matches!(&n.kind, NodeKind::Image(im) if im.link.is_some()); + if (placed || matches!(n.kind, NodeKind::Text(_))) + && let Some(b) = n.visual_bounds() + { + let b = b.inflate(OUTLINE_REACH, OUTLINE_REACH); + out.push(Rect::new((b.x0 - region.x0) * scale, (b.y0 - region.y0) * scale, (b.x1 - region.x0) * scale, (b.y1 - region.y0) * scale)); + } else if let Some(c) = n.children() { + all_type_areas(c, region, scale, out); + } + } +} + +/// Which of `w` × `h` pixels are marked, counted so that the share of any rectangle's pixels that +/// are is read at once. +pub(super) struct Shares { + /// How many of the marked pixels lie above and left of each pixel corner. + sums: Vec, + w: usize, + h: usize, +} + +impl Shares { + /// The pixels `marks` marks (row by row). + pub(super) fn of(marks: &[bool], w: usize, h: usize) -> Self { + let stride = w + 1; + let mut sums = vec![0u32; stride * (h + 1)]; + for (k, marked) in marks.iter().enumerate().take(w * h) { + let (i, j) = (k % w.max(1), k / w.max(1)); + let left = sums.get((j + 1) * stride + i).copied().unwrap_or(0); + let up = sums.get(j * stride + i + 1).copied().unwrap_or(0); + let corner = sums.get(j * stride + i).copied().unwrap_or(0); + if let Some(s) = sums.get_mut((j + 1) * stride + i + 1) { + *s = (left + up + u32::from(*marked)).saturating_sub(corner); + } + } + Self { sums, w, h } + } + + /// The share (0 to 1) of `r`'s pixels that are marked: 0 for one with none of the pixels. + pub(super) fn share(&self, r: &Rect) -> f64 { + let (w, h, stride) = (self.w, self.h, self.w + 1); + let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; + let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + if !r.is_finite() || x1 <= x0 || y1 <= y0 { + return 0.0; + } + let at = |x: usize, y: usize| self.sums.get(y * stride + x).copied().unwrap_or(0); + let inside = (at(x1, y1) + at(x0, y0)).saturating_sub(at(x0, y1) + at(x1, y0)); + f64::from(inside) / ((x1 - x0) as f64 * (y1 - y0) as f64) + } +} + /// Which of `w` × `h` pixels (row by row) lie in one of `areas`. fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec { // Each area adds one inside it: corners marked, then summed along the rows and down the columns. @@ -272,6 +356,10 @@ fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec { (0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect() } +/// The least share of a text object's area (with the margin round it) where the page draws anything +/// or has type, for its type laid out again to count as type. +const MARKED: f64 = 0.05; + /// More of the page than this differing between the layers' art and the page's own, and the /// layers aren't used. pub(super) const MAX_DIFFERENCE: f64 = 0.05; @@ -287,11 +375,13 @@ pub(super) const MAX_SOLID_DIFFERENCE: f64 = 0.001; const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, -/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little: +/// also round it)? An error says they don't; `Ok` has the notes to give when they differ a little: /// with the share of the pixels that differ away from type when that is notable, otherwise with the -/// share of those that differ in the type's areas. -pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result, String> { - let mut diff = view.difference(layered, frame.rect); +/// share of those that differ in the type's areas. With `type_reflow` (all the type laid out again +/// from the file's text, which may show in another font), type that differs doesn't make them +/// differ: only art away from type does, and the type's share is a note of its own. +pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document, type_reflow: bool) -> Result, String> { + let mut diff = view.difference(layered, frame.rect, type_reflow); if frame.whole && let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered)) .filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a)) @@ -302,21 +392,24 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all); diff = Difference { any: diff.any.max(round.any), art: diff.art.max(round.art), solid: diff.solid.max(round.solid) }; } - if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { - return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0)); + if diff.weighed(type_reflow) > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { + return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.weighed(type_reflow) * 100.0)); } if diff.any <= NOTABLE_DIFFERENCE { - return Ok(None); + return Ok(vec![]); } - Ok(Some(if diff.art > NOTABLE_DIFFERENCE { - format!( - "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", - diff.art * 100.0 - ) - } else { - format!( - "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", - (diff.any - diff.art) * 100.0 - ) - })) + let art = format!( + "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", + diff.art * 100.0 + ); + let typed = format!( + "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", + (diff.any - diff.art) * 100.0 + ); + let art_notable = diff.art > NOTABLE_DIFFERENCE; + Ok(match (art_notable, type_reflow && diff.any - diff.art > NOTABLE_DIFFERENCE) { + (true, true) => vec![art, typed], + (true, false) => vec![art], + (false, _) => vec![typed], + }) } diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 4bb3675cd1..6c6cb82b4d 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -1,11 +1,21 @@ use super::layers::closed_where_ends_meet; -use super::slots::{Content, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, words}; +use super::slots::{ + Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, extent, join_pieces, letters, same_type, + words, +}; use super::{Affine, Arc, Node, NodeId, NodeKind, Point, Rect, Story, TextKind}; -/// Match page objects to the nearest slot whose story describes them, including hidden slots. -fn match_page_objects(infos: &[SlotInfo], lines: &[Option>], shown: &[Vec>]) -> Vec> { +/// A slot's type made from the file's text document, and roughly where it lies on the document. +pub(super) type Made = (Box, Option); + +/// Match page objects to the nearest slot that `open` (the slots whose type wasn't made) has and +/// whose story describes them, including hidden slots. +fn match_page_objects(infos: &[SlotInfo], lines: &[Option>], open: &[bool], shown: &[Vec>]) -> Vec> { let mut pairs: Vec<(f64, usize, usize)> = vec![]; for (k, _) in infos.iter().enumerate() { + if !open.get(k).copied().unwrap_or(false) { + continue; + } let Some(l) = lines.get(k).and_then(Option::as_ref) else { continue }; for (j, object) in shown.iter().enumerate() { if let Some(d) = object.iter().filter_map(|n| same_type(n, l)).min_by(f64::total_cmp) { @@ -40,12 +50,139 @@ fn frame_text_from_art(info: &SlotInfo, node: &mut Node, region: &mut Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + warn: &mut Vec, +) -> Vec> { + let mut taller = 0; + let made = infos + .iter() + .enumerate() + .map(|(k, info)| { + let t = template?; + let story = stories.get(k)?.as_ref()?; + let mut node = story.node(NodeId(0), info.frame, t, to_doc)?; + let mut region = story.region(t, to_doc); + // The first line where the file has it, in the text document's frame (that of a + // copied object is its original's, as its lines are). + story.place_first_line(&mut node, t, to_doc); + // Area type and type on a path in the object's own frame: the text document's frame + // of a copied object keeps its original's path. + frame_text_from_art(info, &mut node, &mut region); + if let NodeKind::Text(text) = &mut node.kind + && story.fit_first_line(text) + { + taller += 1; + } + Some((Box::new(node), region)) + }) + .collect(); + if taller > 0 { + warn.push(format!( + "area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise" + )); + } + made +} + +/// Does the file's text document make the type of every slot that shows (at least one does)? +pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option]) -> bool { + infos.iter().any(|i| i.shown) && infos.iter().zip(made).all(|(i, m)| !i.shown || m.is_some()) +} + +/// Each slot's made type, where its slot is (the page's type that shows isn't put anywhere). Shown +/// made type with none of the page's type where it draws is weighed against the page (see +/// `prune_unseen`); the page's type that no made type takes, shown or not, is left out with a note +/// in `warn`. Slots that don't show and whose type isn't made take the page's type that doesn't +/// show (`pages`: the page's text objects that show and that don't), by painting order. +pub(super) fn made_only(infos: &[SlotInfo], made: Vec>, pages: [&[Vec>]; 2], warn: &mut Vec) -> Vec { + let [shown, hidden] = pages; + let mut content = made_content(infos, made); + match see_page_type(&mut content, shown) { + Some(0) => {} + Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), + None => warn.push(PAGE_TYPE_UNCHECKED.into()), + } + fill_hidden(infos, &mut content, hidden); + content +} + +/// The letters and digits of `s`, in any script, in lower case: what is compared of the page's type +/// and made type (the page may spell a mark another way). +fn spelling(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The text of `n`, if it is a text object. +fn plain_text(n: &Node) -> String { + if let NodeKind::Text(t) = &n.kind { t.plain_text() } else { String::new() } +} + +/// The words of the page's text object `o`, each as its [`spelling`], the empty ones left out. +fn object_words(o: &[Arc]) -> Vec { + o.iter().flat_map(|n| plain_text(n).split_whitespace().map(spelling).collect::>()).filter(|w| !w.is_empty()).collect() +} + +/// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws, +/// or where its story lies when it draws nothing. +fn made_content(infos: &[SlotInfo], made: Vec>) -> Vec { + infos + .iter() + .zip(made) + .map(|(info, m)| match m { + Some((node, region)) => { + let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region); + Content::Made(node, drawn.filter(|_| info.shown), false) + } + None => Content::Empty, + }) + .collect() +} + +/// Mark the made type that has at least half of a piece of the page's type where it draws (or round +/// it, as far as strokes round type reach) as type the page draws. How many of the page's text +/// objects no made type takes, shown or not: none that holds a piece of the object has its words +/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`). +fn see_page_type(content: &mut [Content], shown: &[Vec>]) -> Option { + let texts = |o: &[Arc]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::>(); + // Each object's pieces of type, and the words of them that no made type holding it has yet. + let mut objects: Vec<(Vec, Vec, bool)> = + shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect(); + let pieces: usize = objects.iter().map(|o| o.0.len()).sum(); + if content.len().saturating_mul(pieces) > MAX_PAIRS { + return None; + } + let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9); + for c in content { + let Content::Made(node, region, seen) = c else { continue }; + // Hidden made type has no region: where it draws, shown, is its own box. + let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue }; + let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() }; + for (rects, words, held) in &mut objects { + if rects.iter().any(|r| holds(drawn, r)) { + *held = true; + *seen |= region.is_some(); + words.retain(|w| !spelled.contains(w.as_str())); + } + } + } + Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count()) +} + +/// What goes into each of `infos`' slots when the file's text document can't make the type of every +/// slot that shows: type made from the text document (`made`) where it can, else the page's type that +/// the text document puts where the page has it, else the page's type in painting order. The page's +/// type that lies where made type draws and has its words is that type as the page draws it; the +/// rest goes only into slots without made type. pub(super) fn plan( infos: &[SlotInfo], stories: &[Option>], + made: Vec>, template: Option<(f64, f64)>, to_doc: Affine, pages: [&[Vec>]; 2], @@ -59,49 +196,16 @@ pub(super) fn plan( Some(s.line_starts(t).into_iter().map(|(text, (x, y))| (text, to_doc * Point::new(x, y))).collect()) }) .collect(); - let owner = match_page_objects(infos, &lines, shown); - // Type the text document makes, shown or not: the page's pieces of it aren't needed. - let mut content: Vec = infos.iter().map(|_| Content::Empty).collect(); + // A story's lines are its first frame's: a frame of a story whose type is made in another + // text object can't say that the page's type there is its own. + let made_stories: std::collections::BTreeSet = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); + let open: Vec = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); + let owner = match_page_objects(infos, &lines, &open, shown); // Where the made type that doesn't show lies, by slot. - let mut hidden_at: Vec<(usize, Rect)> = vec![]; - let mut taller = 0; - if let Some(t) = template { - for (k, info) in infos.iter().enumerate() { - let Some(Some(story)) = stories.get(k) else { continue }; - let Some(mut node) = story.node(NodeId(0), info.frame, t, to_doc) else { continue }; - let mut region = story.region(t, to_doc); - // The first line where the file has it, in the text document's frame (that of a - // copied object is its original's, as its lines are). - story.place_first_line(&mut node, t, to_doc); - // Area type and type on a path in the object's own frame: the text document's frame - // of a copied object keeps its original's path. - frame_text_from_art(info, &mut node, &mut region); - if let (false, Some(r)) = (info.shown, region) { - hidden_at.push((k, r)); - } - if let NodeKind::Text(text) = &mut node.kind - && story.fit_first_line(text) - { - taller += 1; - } - if let Some(c) = content.get_mut(k) { - *c = Content::Made(Box::new(node), region.filter(|_| info.shown), false, vec![]); - } - } - } - if taller > 0 { - warn.push(format!( - "area type in frames too short for a line of the font it shows in got taller frames ({taller}): their type wouldn't show otherwise" - )); - } - // The file's text document is trusted where it agrees with the page about something (its lines - // start where the page's type does, or the page has type where it lays type out), or where the - // page has no type to disagree with. - let in_region = |object: &[Arc]| covered(object, &content, |_| true); - let trusted = owner.iter().any(Option::is_some) || shown.is_empty() || shown.iter().any(|o| in_region(o)); - if !trusted { - content.iter_mut().for_each(|c| *c = Content::Empty); - } + let hidden_at: Vec<(usize, Rect)> = + infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Type the text document makes, shown or not: the page's pieces of it aren't needed. + let mut content = made_content(infos, made); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) let hidden_type = |object: &[Arc]| { @@ -116,59 +220,45 @@ pub(super) fn plan( }) }) }; - // The letters of each slot's story, in lower case. - let spelled: Vec = stories.iter().map(|s| s.as_ref().map(|s| letters(s.text()).to_ascii_lowercase()).unwrap_or_default()).collect(); - // For each slot: is its made type where `object` is, with the words of one of `object`'s texts in - // its story? All are false unless such slots have the words of every text between them. - let spelling = |object: &[Arc], content: &[Content]| -> Vec { - let r = extent(object); - let texts: Vec> = object + // The letters and digits of each slot's made type that shows, in any script, in lower case. + let spelled: Vec = content + .iter() + .map(|c| match c { + Content::Made(node, Some(_), _) => match &node.kind { + NodeKind::Text(t) => spelling(&t.plain_text()), + _ => String::new(), + }, + _ => String::new(), + }) + .collect(); + // Has made type that draws where `object` lies every word of it ([`spelling`]), in any order? + let made_words = |object: &[Arc], content: &[Content]| { + let Some(r) = extent(object) else { return true }; + let near: Vec<&String> = content .iter() - .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text().to_ascii_lowercase())) } else { None }) - .filter(|ws| !ws.is_empty()) + .zip(&spelled) + .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) + .map(|(_, s)| s) .collect(); - let has = |k: usize| spelled.get(k).is_some_and(|s| texts.is_empty() || texts.iter().any(|ws| ws.iter().all(|w| s.contains(w.as_str())))); - let near: Vec = content - .iter() - .enumerate() - .map(|(k, c)| match (c, r) { - (Content::Made(_, Some(region), ..), Some(r)) => region.intersect(r).area() > 0.0 && has(k), - _ => false, - }) - .collect(); - let every = texts.iter().flatten().all(|w| near.iter().zip(&spelled).any(|(n, s)| *n && s.contains(w.as_str()))); - if every { near } else { vec![] } + object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) }; let mut spare: Vec>> = vec![]; for (j, object) in shown.iter().enumerate() { - let spells = spelling(object, &content); - let spells = |k: usize| spells.get(k).copied().unwrap_or(false); - match owner.get(j).copied().flatten().filter(|_| trusted) { - // The type of a text object the layers hide: the layers have it, hidden, so the page's - // isn't another text object's. - Some(k) if infos.get(k).is_some_and(|i| !i.shown) && matches!(content.get(k), Some(Content::Made(..))) => {} + match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { - Some(Content::Made(_, _, seen, _)) => *seen = true, Some(Content::Page(p)) => p.extend(object.iter().cloned()), Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type is and has that type's words is that type as the page draws it. - None if covered(object, &content, spells) => { - let r = extent(object).unwrap_or(Rect::ZERO); - for (k, c) in content.iter_mut().enumerate() { - if let Content::Made(_, Some(region), seen, _) = c - && !region.intersect(r).is_zero_area() - && spells(k) - { - *seen = true; - } - } - } - None if trusted && hidden_type(object) => {} + // What lies where made type draws, with its words, is that type as the page draws it (in + // another font, maybe, and in any script). + None if covered(object, &content, |_| true) && made_words(object, &content) => {} + None if hidden_type(object) => {} None => spare.push(object.clone()), } } + // The page's type that no made type takes is the spare type below. + let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { if let (Content::Page(parts), Some(Some(l))) = (c, lines.get(k)) { join_pieces(parts, l); @@ -179,12 +269,11 @@ pub(super) fn plan( infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); if loose.is_empty() { // Type of the page that no text object says it owns goes with the nearest text object that has - // type of the page; with none, it is left out. + // type of the page (never into made type); with none, it is left out. let mut left_out = false; for object in &spare { let (centre, near) = (extent(object).map(|r| r.center()), |c: &Content| match c { Content::Page(parts) => extent(parts).map(|r| r.center()), - Content::Made(_, region, ..) => region.map(|r| r.center()), _ => None, }); let nearest = content @@ -192,14 +281,14 @@ pub(super) fn plan( .filter_map(|c| near(c).zip(centre).map(|(p, q)| ((p.x - q.x).hypot(p.y - q.y), c))) .min_by(|a, b| a.0.total_cmp(&b.0)); match nearest { - Some((_, Content::Page(parts) | Content::Made(_, _, _, parts))) => parts.extend(object.iter().cloned()), + Some((_, Content::Page(parts))) => parts.extend(object.iter().cloned()), _ => left_out = true, } } if !spare.is_empty() { warn.push( if left_out { - "some of the page's type has no text object in the layers, so it is left out" + PAGE_TYPE_LEFT_OUT } else { "some of the page's type has no text object of its own in the layers, so it is with another's" } @@ -221,13 +310,50 @@ pub(super) fn plan( warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into()); } } - // The same for the slots that don't show. + fill_hidden(infos, &mut content, hidden); + content +} + +/// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't +/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object +/// with words and at least half of it where such type draws, while the type has all its words left +/// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes. +fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec>]) { let unread: Vec = infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); - for (slot, parts) in unread.iter().zip(assign(hidden, unread.len())) { + if unread.is_empty() { + return; + } + // Where each made type that doesn't show draws, and the letters it has left. + let mut made: Vec<(Rect, String)> = content + .iter() + .filter_map(|c| match c { + Content::Made(node, None, _) => node.visual_bounds().map(|b| (b.inflate(OUTLINE_REACH, OUTLINE_REACH), spelling(&plain_text(node)))), + _ => None, + }) + .collect(); + let pairs = made.len().saturating_mul(hidden.len()); + // Is `o` the type of made type that doesn't show? That type's letters for it are taken. + let mut theirs = |o: &[Arc]| { + let words = object_words(o); + let Some(r) = extent(o).filter(|_| !words.is_empty()) else { return false }; + let found = made.iter_mut().find_map(|(b, s)| { + if b.intersect(r).area() < 0.5 * r.area().max(1e-9) { + return None; + } + let mut left = s.clone(); + for w in &words { + let at = left.find(w.as_str())?; + left.replace_range(at..at + w.len(), ""); + } + Some((s, left)) + }); + found.map(|(s, left)| *s = left).is_some() + }; + let hidden: Vec>> = if pairs > MAX_PAIRS { hidden.to_vec() } else { hidden.iter().filter(|o| !theirs(o)).cloned().collect() }; + for (slot, parts) in unread.iter().zip(assign(&hidden, unread.len())) { if let Some(c) = content.get_mut(*slot) { *c = Content::Page(parts.into_iter().flat_map(|p| p.iter().cloned()).collect()); } } - content } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 1548a2e9af..e6dc909ace 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -9,13 +9,23 @@ pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn' pub(super) const ART_LEFT_OUT: &str = "hidden layers have art this can't read"; +/// The page's type that no text object takes, left out. +pub(super) const PAGE_TYPE_LEFT_OUT: &str = "some of the page's type has no text object in the layers, so it is left out"; + +/// The page's type, too much to check against the text objects (it may have some that none takes). +pub(super) const PAGE_TYPE_UNCHECKED: &str = + "the page's type wasn't checked against the text objects, as there is too much of it: some of it may have no text object"; + pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read"; /// Does this import note say that the file has something the document doesn't (hidden text, art or -/// layers that could not be read)? Writing the document over the file would lose it for good. +/// layers that could not be read, or the page's type that no text object takes or may not take)? +/// Writing the document over the file would lose it for good. pub fn is_loss(note: &str) -> bool { note.ends_with(TEXT_LEFT_OUT) || note.ends_with(TYPE_LEFT_OUT) + || note == PAGE_TYPE_LEFT_OUT + || note == PAGE_TYPE_UNCHECKED || [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n)) } @@ -163,10 +173,9 @@ pub(super) fn assign(objects: &[Vec>], slots: usize) -> Vec>), - /// A text object made from the file's text document, where it lies on the document, whether - /// the page has type where it is, and the page's type of no text object that is nearest it - /// (kept after it). - Made(Box, Option, bool, Vec>), + /// A text object made from the file's text document, where it draws on the document (when it + /// shows), and whether the page has type where it is. + Made(Box, Option, bool), /// Nothing the file lets this read. Empty, /// Its type is on the page with another text object's; there is nothing to put here. @@ -252,7 +261,7 @@ pub(super) fn fill_slots( i += n; continue; } - Some(Content::Made(mut text, _, seen, extra)) => { + Some(Content::Made(mut text, _, seen)) => { text.id = doc.alloc_id(); if let Some(story) = story { made.push((story, frame, text.id)); @@ -265,20 +274,12 @@ pub(super) fn fill_slots( } // Type the page shows is kept; other made type is weighed against the page. text.name = if seen { name.cloned() } else { Some(format!("{MADE}{}", name.map_or("", String::as_str))) }; - let extra: Vec> = extra.iter().map(|p| reid(doc, p)).collect(); - // The type takes the slot's transparency; the page's type kept after it, where it has - // none of its own, goes into a group with it that has the transparency instead. - let parts: Vec> = if transparent && !extra.is_empty() && !extra.iter().any(|p| see_through(p)) { - let mut group = Node::group(doc.alloc_id(), std::iter::once(Arc::new(*text)).chain(extra).collect()); - (group.opacity, group.blend, group.isolate, group.knockout) = state; - vec![Arc::new(group)] - } else { - (text.opacity, text.blend, text.isolate, text.knockout) = state; - std::iter::once(Arc::new(*text)).chain(extra).collect() - }; - let n = parts.len(); - nodes.splice(i..=i, parts); - i += n; + // The type takes the slot's transparency. + (text.opacity, text.blend, text.isolate, text.knockout) = state; + if let Some(slot) = nodes.get_mut(i) { + *slot = Arc::new(*text); + } + i += 1; continue; } Some(Content::Merged) => { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index ee4beca057..29e73bbc92 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -342,6 +342,24 @@ fn type_of_the_page_inside_a_placed_file_needs_no_text_object() { assert!(!read, "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("its layers have no text objects")), "{warnings:?}"); } + // With a text object the text document makes beside it, the placed file's type is still its + // own, not type left out. + // The template box's centre (100, 50) is the canvas centre: the anchor is at (5, 10) in the art. + let doc = text_document(&[("Note\r", 0, (8096.5, 8231.5), (0.0, 0.0), 0.0)]); + let both = native_with_text(&layer("Pages", true, &format!("{place}{}", text_object(0))), &doc) + .replace("%AI3_TemplateBox: 50 50 50 50", "%AI3_TemplateBox: 100 50 100 50"); + let mut page = pdf(38.0); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let note = Node::new( + page.alloc_id(), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 90.0), "Note", style))), + ); + let layer_id = page.layers[0].id; + page.insert(Some(layer_id), 2, note).unwrap(); + let (d, warnings, read) = crate::layered_ai(&private(&both), page, vec![], false, false, 1.0); + assert!(read, "{warnings:?}"); + assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::>(), ["Note"], "{warnings:?}"); + assert!(!warnings.iter().any(|w| w.contains("left out")), "{warnings:?}"); } /// A palette of `[None]` and White, and a color group `Inks` holding a spot color, Red ink. @@ -979,38 +997,83 @@ fn a_line_the_page_draws_in_pieces_goes_to_its_text_object_whole() { assert!(t.cached_bounds.is_none() && t.cached_baselines.is_empty()); } -#[test] -fn type_of_the_page_that_no_story_places_stays_with_the_nearest_text_object() { - let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); - let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); - let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; - let r = import(&eps(page, &art)).unwrap(); - let mut all = vec![]; - r.document.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - all.push(t.plain_text()); - } - }); - assert!(all.contains(&"Extra".to_string()), "{all:?} {:?}", r.warnings); +/// `doc` (from [`text_document`], whose stories all name the first frame) with its last story in +/// its own frame, the last, of a kind this doesn't read. +fn last_frame_unread(doc: &str) -> String { + let frames = doc.matches("/2 << /2 [").count(); + let mut doc = doc.to_string(); + let at = doc.rfind("/1 << /0 [ << /0 0 >> ]").unwrap(); + doc.replace_range(at..at + 23, &format!("/1 << /0 [ << /0 {} >> ]", frames - 1)); + let at = doc.rfind("/2 << /2 [").unwrap() + "/2 << ".len(); + doc.insert_str(at, "/0 9 "); + doc } -/// Page type of no text object that lies where made type is, but has other letters, is not that type: -/// it stays, with the nearest text object. -#[test] -fn type_of_the_page_near_made_type_with_other_letters_stays() { - // "Extra" is 11.5 below the line of "Hi there", well inside the box round that line. - let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); - let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); - let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 50 moveto (Extra) show"; - let r = import(&eps(page, &art)).unwrap(); +/// The plain text of every text object in `d`, in order. +fn all_texts(d: &Document) -> Vec { let mut all = vec![]; - r.document.walk(|n| { + d.walk(|n| { if let NodeKind::Text(t) = &n.kind { all.push(t.plain_text()); } }); - assert_eq!(all, ["Hi there", "Extra"], "{:?}", r.warnings); - assert!(r.warnings.iter().any(|w| w.contains("with another's")), "{:?}", r.warnings); + all +} + +/// Type of the page that no story places goes to the text object whose type the text document +/// can't make, not into made type; with no such text object and none of the page's type in a text +/// object, it is art the layers don't draw, which the comparison weighs. +#[test] +fn type_of_the_page_that_no_story_places_goes_to_a_text_object_that_cant_be_made() { + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{:?}", r.warnings); + // Every text object's type made: the page's "Extra" is in none of them, so the file comes in as its page. + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let r = import(&eps(page, &native_with_text(&layer("Art", true, &text_object(0)), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// A story whose first frame's type is made and whose second frame's can't be: the page's type of +/// the first frame stays the made type's, and isn't the second frame's too. +#[test] +fn page_type_of_a_made_frame_isnt_given_to_the_storys_other_frame() { + let mut doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Spare\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]); + // Story 0 in frames 0 and 1, both point type: point type isn't threaded, so its second frame has none. + let at = doc.find("/1 << /0 [ << /0 0 >> ]").unwrap(); + doc.replace_range(at..at + 23, "/1 << /0 [ << /0 0 >> << /0 1 >> ]"); + let art = native_with_text(&layer("Art", true, &(frame_object(0, 0) + &frame_object(0, 1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); +} + +/// Page type of no text object that lies where made type draws, with its words in any case, is that +/// type as the page draws it, and doesn't go to a text object whose type can't be made. Page type +/// with other words there, or beside made type, does. +#[test] +fn type_of_the_page_where_made_type_draws_with_its_words_is_that_type() { + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8200.0, 8120.0), (0.0, 0.0), 0.0)])); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let with = |drawn: &str, y: f64| { + format!("0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 {y} moveto ({drawn}) show") + }; + // "THERE" over the line of "Hi there", a point below it. + let r = import(&eps(&with("THERE", 60.5), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("1 text objects")), "{:?}", r.warnings); + // "Extra" there, or 11.5 below that line: the text object that can't be made takes it. + for y in [60.5, 50.0] { + let r = import(&eps(&with("Extra", y), &art)).unwrap(); + assert_eq!(all_texts(&r.document), ["Hi there", "Extra"], "{y}: {:?}", r.warnings); + } } /// Page type of no text object that lies where made type is and has its letters, in any case, is that @@ -1075,22 +1138,23 @@ fn type_of_the_page_with_the_letters_of_two_made_types_where_it_lies_is_their_ty } /// The file's text document is trusted where the page has type where it lays type out, whatever -/// letters that type has: its type is weighed against the page. +/// letters that type has: the type is the text document's, and the difference is noted as type. +/// The page's type with other words is left out, with a note that is a loss. #[test] fn page_type_where_made_type_is_trusts_the_text_document_whatever_its_letters() { let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (Extra) show"; let r = import(&eps(page, &art)).unwrap(); - let mut all = vec![]; - r.document.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - all.push(t.plain_text()); - } - }); - assert_eq!(all, ["Extra"], "{:?}", r.warnings); - // "Hi there" was made from the text document and left out because the page doesn't draw it. - assert!(r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("doesn't draw")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("so it is left out") && crate::is_loss(w)), "{:?}", r.warnings); + // The page's type with the text document's words, in capitals: nothing is left out. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 50 moveto (HI THERE) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(all_texts(&r.document), ["Hi there"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); } #[test] @@ -1161,15 +1225,6 @@ fn type_keeps_the_opacity_and_blend_mode_of_its_text_object() { let art = native_with_text(&layer("Art", true, &(drawing.clone() + &format!("{own}1 (Style) XW\n").repeat(50))), &doc); let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); assert_eq!(depth(&d.layers[0]), 4, "{notes:?}"); - // Made type with the page's type of no text object kept after it: a group of the two has it. - let art = native_with_text(&layer("Art", true, &format!("1 0.2 0 0 0 Xy\n{}", text_object(0))), &doc); - let r = import(&eps(&format!("{page} 58.5 30 moveto (Extra) show"), &art)).unwrap(); - assert_eq!(kinds(&r.document.layers[0]), ["group[2]"], "{:?}", r.warnings); - let group = &r.document.layers[0].children().unwrap()[0]; - assert_eq!((group.opacity, group.blend), (0.2, BlendMode::Multiply)); - let texts: Vec = text_of(group).iter().map(|t| t.plain_text()).collect(); - assert_eq!(texts, ["Hi there", "Extra"]); - assert!(group.children().unwrap().iter().all(|p| (p.opacity, p.blend) == (1.0, BlendMode::Normal))); // A story in a frame of a kind this doesn't know: the type that shows is the page's. An EPS page has // no transparency, so its type takes its text object's. let doc = doc.replace("/2 << /2 [ 1 0 0 1 0 0 ] >>", "/2 << /0 9 /2 [ 1 0 0 1 0 0 ] >>"); @@ -1296,8 +1351,9 @@ fn a_run_longer_than_any_text_doesnt_overflow() { #[test] fn more_text_objects_than_are_matched_leave_the_page() { + // Text objects whose type the text document can't make are matched with the page's type. let many = text_object(0).repeat(5001); - let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let doc = last_frame_unread(&text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)])); let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &many)), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); assert_eq!(names(&r.document), ["Back", "Spare", "Layer 1"], "{:?}", r.warnings); @@ -1440,8 +1496,10 @@ fn art_the_page_doesnt_draw_is_noted_with_its_own_share_and_not_the_types() { let r = import(&page_in_pieces_and_layers(bar)).unwrap(); assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); let notes: Vec<&String> = r.warnings.iter().filter(|w| w.contains("differs from the file's own page")).collect(); - assert_eq!(notes.len(), 1, "{:?}", r.warnings); + // The type, all laid out again from the text document, has a note of its own. + assert_eq!(notes.len(), 2, "{:?}", r.warnings); assert!(notes[0].starts_with("the art on the layers differs from the file's own page in about 0.4% of it (brush strokes"), "{notes:?}"); + assert!(notes[1].starts_with("the type on the layers differs from the file's own page"), "{notes:?}"); } /// An EPS whose page is its art's box `[x0 y0 x1 y1]` (not its artboard, 0 0 100 100), drawing @@ -1587,6 +1645,258 @@ fn area_type_and_type_on_a_path_come_from_the_text_document() { assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); } +/// A point type frame at the point (`x`, `y`) of the art. +fn point_frame(x: f64, y: f64) -> String { + let (cx, cy) = canvas(x, y); + format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {cx} {cy} ] >> >> >>") +} + +/// An area type frame of the rectangle `x0 y0 x1 y1` of the art. +fn area_frame(x0: f64, y0: f64, x1: f64, y1: f64) -> String { + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(x0, y0, x1, y1)) +} + +/// The text of `n` when it is a text object, or a group of one object whose text that is. +fn lone_text(n: &Node) -> Option { + match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + NodeKind::Group { .. } => match n.children()?.as_slice() { + [only] => lone_text(only), + _ => None, + }, + _ => None, + } +} + +/// What each object of layer `l` holds as one text object ([`lone_text`]). +fn lone_texts(l: &Node) -> Vec> { + l.children().into_iter().flatten().map(|n| lone_text(n)).collect() +} + +/// `text` as a string of the text document: UTF-16 after its byte order mark, each byte in octal. +fn utf16(text: &str) -> String { + let mut out = String::from("\\376\\377"); + for unit in text.encode_utf16() { + for b in unit.to_be_bytes() { + out.push_str(&format!("\\{b:03o}")); + } + } + out +} + +/// Type the text document makes for every text object that shows stays in each one's own group, +/// on its own layer, however the page draws it: in pieces, in another order, with a quote hung +/// outside its frame. +#[test] +fn type_from_the_text_document_stays_in_its_groups() { + let frames = [ + point_frame(10.0, 90.0), + point_frame(10.0, 78.0), + point_frame(55.0, 90.0), + area_frame(10.0, 40.0, 45.0, 55.0), + area_frame(55.0, 40.0, 90.0, 55.0), + ]; + let style = "/1 8.0"; + let doc = document_of( + &frames, + &[ + story("Alpha\\r", &[0], "/0 0", style), + story("Bravo\\r", &[1], "/0 0", style), + story("Charlie\\r", &[2], "/0 0", style), + story("\"Delta\"\\r", &[3], "/0 0", style), + story("\"Echo\"\\r", &[4], "/0 0", style), + ], + ); + let nested = |s: u32| format!("u\nu\n{}U\nU\n", frame_object(s, 0)); + let single = |s: u32| format!("u\n{}U\n", frame_object(s, 0)); + let words = layer("Words", true, &(nested(0) + &nested(1) + &single(3))); + let more = layer("More", true, &(single(2) + &nested(4))); + let art = native_with_text(&(words + &more), &doc); + // The page paints the third story before the first, each in two pieces, and hangs the area + // type's opening quotes outside their frames, painted last. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont \ + 55 90 moveto (Char) show 72.3 90 moveto (lie) show 10 90 moveto (Al) show 17.1 90 moveto (pha) show \ + 10 78 moveto (Bravo) show 10 48.5 moveto (Delta\") show 55 48.5 moveto (Echo\") show \ + 7.2 48.5 moveto (\") show 52.2 48.5 moveto (\") show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Words", "More"], "{:?}", r.warnings); + let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::>(); + assert_eq!(lone_texts(&r.document.layers[0]), some(&["Alpha", "Bravo", "\"Delta\""]), "{:?}", r.warnings); + assert_eq!(lone_texts(&r.document.layers[1]), some(&["Charlie", "\"Echo\""]), "{:?}", r.warnings); + assert_eq!(all_texts(&r.document).len(), 5, "{:?}", r.warnings); +} + +/// The page's type isn't matched with the text objects when the text document makes the type of +/// every one: a file of more of them than are matched still comes in with its layers. +#[test] +fn six_thousand_point_stories_open_with_layers() { + let stories: Vec<(String, (f64, f64))> = + (0..6000).map(|i| (format!("S{i}\r"), (8150.0 + f64::from(i % 60), 8150.0 + f64::from(i / 60) * 0.8))).collect(); + let list: Vec> = stories.iter().map(|(t, at)| (t.as_str(), 0, *at, (0.0, 0.0), 0.0)).collect(); + let doc = text_document(&list); + let objects: String = (0..6000).map(text_object).collect(); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &objects)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + assert_eq!(names(&d), ["Back", "Words"], "{notes:?}"); + assert_eq!(text_of(&d.layers[1]).len(), 6000, "{notes:?}"); +} + +/// A story in a frame of a kind this doesn't read takes the page's type for its own text object +/// only: the others keep the type made from the text document, in their groups, and the page's +/// type beside made type, with its letters, goes to the text object that can't be made. +#[test] +fn a_story_with_an_unknown_frame_kind_falls_back_for_that_slot_only() { + let doc = last_frame_unread(&text_document(&[ + ("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Low\r", 0, (8160.0, 8221.5), (0.0, 0.0), 0.0), + ("Hi\r", 0, (8200.0, 8191.5), (0.0, 0.0), 0.0), + ])); + let grouped = |s: u32| format!("u\n{}U\n", text_object(s)); + let art = native_with_text(&layer("Art", true, &(grouped(0) + &grouped(1) + &grouped(2))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 18.5 20 moveto (Low) show \ + 58.5 50 moveto (Hi) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let some = |v: &[&str]| v.iter().map(|s| Some(s.to_string())).collect::>(); + assert_eq!(lone_texts(&r.document.layers[0]), some(&["Hi there", "Low", "Hi"]), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); +} + +/// Type laid out from the text document that the page draws differently (in another font, where +/// the file's isn't installed) keeps the layers, with a note; art that differs still doesn't. +#[test] +fn type_drawn_in_another_font_keeps_the_layers() { + let lines = [("Hello\r", 8221.5), ("World\r", 8201.5), ("Again\r", 8181.5), ("Today\r", 8161.5)]; + let list: Vec> = lines.iter().map(|(t, y)| (*t, 0, (8146.5, *y), (0.0, 0.0), 0.0)).collect(); + let doc = text_document(&list).replace("/1 14.0", "/1 20.0"); + let objects: String = (0..4).map(text_object).collect(); + // The page draws each line in capitals: a font that isn't this one. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 20 scalefont setfont \ + 5 85 moveto (HELLO) show 5 65 moveto (WORLD) show 5 45 moveto (AGAIN) show 5 25 moveto (TODAY) show"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert_eq!(all_texts(&r.document), ["Hello", "World", "Again", "Today"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings); + // A square the page doesn't draw, away from the type: the file comes in as its page. + let block = "0 0 0 1 k\n80 5 m\n90 5 L\n90 15 L\n80 15 L\nf\n"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &format!("{block}{objects}")), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// Type laid out from the text document where the page draws nothing is art the page lacks, even +/// with more such text objects than are weighed one by one against the page. +#[test] +fn type_the_page_doesnt_draw_on_bare_page_still_differs() { + let mut list: Vec> = vec![("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]; + for i in 0..14 { + list.push(("Gm\r", 0, (8146.5 + f64::from(i % 4) * 22.0, 8216.5 + f64::from(i / 4) * 18.0), (0.0, 0.0), 0.0)); + } + let doc = text_document(&list); + let objects: String = (0..15).map(text_object).collect(); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &native_with_text(&layer("Art", true, &objects), &doc))).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings); +} + +/// A hidden text object whose type the text document can't make takes the page's hidden type, as +/// it does when some shown text object's type can't be made either, but not the page's hidden type +/// of one whose type is made. +#[test] +fn a_hidden_text_object_that_cant_be_made_takes_the_pages_hidden_type() { + let doc = last_frame_unread(&text_document(&[ + ("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), + ("Known\rMore\r", 0, (8200.0, 8200.0), (0.0, 0.0), 0.0), + ("Secret\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0), + ])); + let spare = layer("Spare", false, &(text_object(1) + &text_object(2))); + let art = native_with_text(&(layer("Art", true, &format!("{}\n{}", square(10, 10), text_object(0))) + &spare), &doc); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let text = |d: &mut Document, s: &str, y: f64| { + Node::new(d.alloc_id(), NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(58.5, y), s, style.clone())))) + }; + // The last text object's type over "Known", in words or in marks only. + for secret in ["Secret", "?!"] { + let mut page = pdf_part(10.0, 86.0); + let shown = text(&mut page, "Hi there", 38.5); + let first = page.layers[0].id; + page.insert(Some(first), 1, shown).unwrap(); + let spare = page.add_layer(Some("Spare")); + // The two lines of "Known More" where its story puts them, and the other over them, painted + // first. + for (i, (s, y)) in [(secret, 60.0), ("Known", 58.5), ("More", 73.0)].into_iter().enumerate() { + let n = text(&mut page, s, y); + page.insert(Some(spare), i, n).unwrap(); + } + if let Some(l) = page.node_mut(spare) { + l.visible = false; + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{secret}: {w:?}"); + assert_eq!(names(&d), ["Art", "Spare"], "{w:?}"); + let texts = |l: usize| text_of(&d.layers[l]).iter().map(|t| t.plain_text()).collect::>(); + assert_eq!((texts(0), texts(1)), (vec!["Hi there".to_string()], vec!["Known\nMore".to_string(), secret.to_string()]), "{w:?}"); + } +} + +/// A small label the page draws where no text object of the layers has type differs too little to +/// send the file to its page: the import says it is left out. Type the page draws of a hidden +/// text object isn't counted. +#[test] +fn a_small_label_of_the_page_in_no_text_object_is_noted() { + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Extra\r", 0, (8200.0, 8211.5), (0.0, 0.0), 0.0)]); + let art = native_with_text(&(layer("Art", true, &text_object(0)) + &layer("Spare", false, &text_object(1))), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show 58.5 30 moveto (Extra) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("so it is left out")), "{:?}", r.warnings); + let label = format!("{page} /Helvetica findfont 3 scalefont setfont 10 90 moveto (no.) show"); + let r = import(&eps(&label, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art", "Spare"], "{:?}", r.warnings); + let note = r.warnings.iter().find(|w| *w == "some of the page's type has no text object in the layers, so it is left out"); + assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// A line break inside a paragraph (`\x03` in the text document) stays a line break in it. +#[test] +fn a_soft_return_is_a_line_break_in_its_paragraph() { + let doc = text_document(&[("One\\003Two\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Words", true, &text_object(0))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let texts = text_of(&d.layers[1]); + assert_eq!(texts.len(), 1, "{notes:?}"); + assert_eq!(texts[0].plain_text(), "One\u{2028}Two"); + assert!(texts[0].paras.is_empty(), "one paragraph: {:?}", texts[0].paras); +} + +/// A Thai story is one text object however the page splits its type: by word, and its marks +/// above apart from their letters, above the top of its frame. +#[test] +fn a_thai_story_stays_one_text_object() { + let thai = "\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E31}\u{0E19}\u{0E15}\u{0E4C} \u{0E27}\u{0E31}\u{0E19}\u{0E40}\u{0E01}\u{0E34}\u{0E14}"; + let doc = document_of(&[area_frame(10.0, 30.0, 90.0, 60.0)], &[story(&utf16(&format!("{thai}\r")), &[0], "/0 0", "/1 14.0")]); + let art = native_with_text(&layer("Art", true, &format!("{}\nu\n{}U\n", square(10, 10), frame_object(0, 0))), &doc); + let mut page = pdf_part(10.0, 86.0); + let layer_id = page.layers[0].id; + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + // Doc y 40 is the frame's top: the words on its first line, the marks a little above it. + let pieces = [ + ("\u{0E2A}\u{0E38}\u{0E02}\u{0E2A}\u{0E19}\u{0E15}", 10.0, 53.0), + ("\u{0E27}\u{0E19}\u{0E40}\u{0E01}\u{0E14}", 50.0, 53.0), + ("\u{0E31}\u{0E4C}", 24.0, 41.0), + ("\u{0E31}\u{0E34}", 58.0, 41.0), + ]; + for (i, (text, x, y)) in pieces.iter().enumerate() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(*x, *y), text, style.clone()); + let n = Node::new(page.alloc_id(), NodeKind::Text(Box::new(t))); + page.insert(Some(layer_id), 1 + i, n).unwrap(); + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Art"], "{w:?}"); + assert_eq!(all_texts(&d), [thai], "{w:?}"); + assert_eq!(lone_texts(&d.layers[0]).last(), Some(&Some(thai.to_string())), "{w:?}"); +} + /// A story of `text` on frame 0 whose layout sets glyphs `advance` wide round the outside of a /// circle of radius `radius`, the circle's length between their centres `fraction` of an advance. fn round_story(text: &str, advance: f64, radius: f64, fraction: f64) -> String { diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 83d3e7e01f..6e6ba05847 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -119,6 +119,8 @@ pub(crate) struct Scene<'a> { brushes: Option>, /// Image keys → what draws them (`None`: left out). images: HashMap>>, + /// The source key and solid paint together identify a colorized encoding. + colorized_images: HashMap<(String, String), Option>>, /// Symbols and brush art being written inside one another. nest: u32, } @@ -137,6 +139,7 @@ impl<'a> Scene<'a> { warnings: vec![], brushes: None, images: HashMap::new(), + colorized_images: HashMap::new(), nest: 0, } } @@ -297,7 +300,15 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => self.image(&im.key, self.doc.image_blob(im), im.width, im.height, im.xf), + NodeKind::Image(im) => { + let blob = self.doc.image_blob(im); + match n.extras().colorize.as_deref() { + Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { + self.colorized_image(&im.key, blob, im.width, im.height, im.xf, p); + } + _ => self.image(&im.key, blob, im.width, im.height, im.xf), + } + } NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST @@ -886,6 +897,149 @@ impl<'a> Scene<'a> { } } + /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; + /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. + fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { + let place = xf * Affine::scale_non_uniform(f64::from(width.max(1)), f64::from(height.max(1))); + if !invertible(place) { + return; + } + let cache = (key.to_string(), format!("{paint:?}")); + let encoded = match self.colorized_images.get(&cache) { + Some(e) => e.clone(), + None => { + let e = self.encode_colorized(blob, paint).map(Arc::new); + self.colorized_images.insert(cache, e.clone()); + e + } + }; + if let Some(e) = encoded { + self.place_image(&e, place); + } + } + + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { + let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { + self.warn(UNDECODED); + return None; + }; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS { + self.warn(LARGE_IMAGE); + return None; + } + let Paint::Solid { color, swatch, tint } = paint else { return None }; + let ink = self.solid(color, swatch.as_deref(), *tint); + let binary = coverage.iter().all(|&v| v == 0 || v == 255); + let clear = coverage.contains(&0); + if coverage.iter().any(|&v| v > 0 && v < 255) { + self.warn(IMAGE_PARTLY); + } + let keyed = !binary && clear && self.o.level == Level::Three; + if !binary && clear && !keyed { + self.warn(IMAGE_ALPHA_L2); + } + // Zero tint is uncommon for covered spot pixels; process uses the same rare key as + // ordinary images. Nudge a covered collision so only clear pixels match the mask. + let key = match ink { + Ink::Spot { .. } => [0, 0, 0, 0], + Ink::Process(Space::Gray, ..) => [0, 0, 0, 0], + Ink::Process(..) => [255, 0, 255, 0], + }; + let mut data = Vec::new(); + if binary { + let stride = (w as usize).div_ceil(8); + data.resize(stride.saturating_mul(h as usize), 0); + for (i, &v) in coverage.iter().enumerate() { + if v == 255 + && let Some(byte) = data.get_mut((i / w as usize) * stride + (i % w as usize) / 8) + { + *byte |= 0x80 >> (i % w as usize % 8); + } + } + } else { + for &v in &coverage { + if v == 0 && keyed { + let n = match ink { + Ink::Spot { .. } => 1, + Ink::Process(space, ..) => space.n(), + }; + data.extend(key.iter().take(n)); + continue; + } + let a = f32::from(v) / 255.0; + match ink { + Ink::Spot { tint, .. } => { + let mut sample = (255.0 * tint * a).round() as u8; + if keyed && sample == key[0] { + sample = 1; + } + data.push(sample); + } + Ink::Process(space, components) => { + let paper = if space == Space::Cmyk { 0.0 } else { 1.0 }; + let n = space.n(); + let mut samples = [0; 4]; + for (sample, &component) in samples.iter_mut().zip(components.iter()).take(n) { + *sample = (255.0 * (paper + (component - paper) * a)).round() as u8; + } + if keyed && samples.iter().take(n).eq(key.iter().take(n)) { + samples[if n > 1 { 1 } else { 0 }] = 1; + } + data.extend(samples.iter().take(n)); + } + } + } + } + let (filter, encoded) = match self.o.level { + Level::Three => ("/FlateDecode", ps::deflate(&data)), + Level::Two => { + let mut rl = Vec::new(); + ps::packbits(&data, &mut rl); + rl.push(128); + ("/RunLengthDecode", rl) + } + }; + let mut out = String::new(); + if binary { + // imagemask takes its current ink from the graphics state. + out.push_str(&self.ink_code(ink)); + } else { + match ink { + Ink::Spot { space, .. } => { + let _ = writeln!(out, "VCsp{space} setcolorspace"); + } + Ink::Process(space, ..) => { + let _ = writeln!(out, "{} setcolorspace", space.name()); + } + } + } + let n = match ink { + Ink::Spot { .. } => 1, + Ink::Process(space, ..) => space.n(), + }; + let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; + let _ = write!( + out, + "{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", + if keyed { 4 } else { 1 }, + if binary { 1 } else { 8 }, + ); + if keyed { + let mask: Vec = key.iter().take(n).map(|v| format!("{v} {v}")).collect(); + let _ = write!(out, " /MaskColor [{}]", mask.join(" ")); + } + let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" }); + out.push_str(&ps::ascii85(&encoded)); + Some(out) + } + + /// Ink-setting operators in the cached stencil body, built with the same path as solid fills. + fn ink_code(&mut self, ink: Ink) -> String { + let body = std::mem::take(&mut self.body); + self.set_ink(ink); + std::mem::replace(&mut self.body, body) + } + /// Image `blob` as RGBA pixels; `None` (with a warning) when it can't be written. fn decode_image(&mut self, blob: Option<&ImageBlob>) -> Option { let Some(img) = blob.and_then(|blob| image::load_from_memory(&blob.bytes).ok()) else { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 40eade3b59..c8271dda81 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -331,6 +331,187 @@ fn unpack(data: &[u8]) -> Vec { out } +fn colorized_doc(gray: Vec, paint: Option) -> Document { + let mut d = Document::new(200.0, 200.0); + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), global: true, spot: true }); + let mut png = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(gray.len() as u32, 1, gray).unwrap()) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + d.images.insert("gray".into(), ImageBlob::png(png)); + let im = ImageObject { + key: "gray".into(), + width: 3, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().colorize = paint.map(Box::new); + d.insert(d.default_layer(), 0, n).unwrap(); + d +} + +fn one_bit_blob() -> ImageBlob { + // Uncompressed two-pixel TIFF, BlackIsZero; black then white. + let entries: [(u16, u16, u32); 9] = + [(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)]; + let mut bytes = b"II*\0".to_vec(); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&9u16.to_le_bytes()); + for (tag, kind, value) in entries { + bytes.extend_from_slice(&tag.to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&value.to_le_bytes()); + } + bytes.extend_from_slice(&0u32.to_le_bytes()); + bytes.push(0b0100_0000); + ImageBlob::new("image/tiff", bytes) +} + +fn colorized_samples(d: &Document, level: Level) -> (String, Vec, Vec) { + let out = export(d, &EpsOptions { level, ..opts(d) }, None, None).unwrap(); + let ps = text(&out); + checked_page(&ps); + let encoded = image_data(&ps); + let samples = if level == Level::Three { ps::inflate(&encoded, 1 << 20).unwrap() } else { unpack(&encoded) }; + (ps, samples, out.warnings) +} + +#[test] +fn binary_colorized_images_are_ink_stencils_at_both_levels() { + for (paint, setup) in [ + (Paint::solid(Color::rgb8(255, 0, 0)), "1 0 0 rg"), + (Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 0.5 }, "VCsp0 setcolorspace 0.5 setcolor"), + (Paint::registration(), "VCsp0 setcolorspace 1 setcolor"), + ] { + let d = colorized_doc(vec![0, 255, 0], Some(paint.clone())); + for level in [Level::Two, Level::Three] { + let (ps, samples, warnings) = colorized_samples(&d, level); + assert!(ps.contains("imagemask") && ps.contains("/BitsPerComponent 1 /Decode [1 0]"), "{ps}"); + assert!(ps.contains(setup), "{ps}"); + assert_eq!(samples, vec![0b1010_0000]); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(ps.contains(if level == Level::Two { "/RunLengthDecode" } else { "/FlateDecode" })); + if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + assert!(ps.contains("/Separation")); + } + if paint.is_registration() { + assert!(ps.contains("/All /DeviceCMYK")); + assert!(dsc(&ps, "DocumentCustomColors").is_none()); + } else if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)")); + } + } + } +} + +#[test] +fn one_bit_source_uses_the_same_stencil_coverage() { + let mut d = colorized_doc(vec![0, 255, 255], Some(Paint::solid(Color::rgb8(0, 0, 255)))); + d.images.insert("gray".into(), one_bit_blob()); + let id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(id).unwrap().kind { + im.width = 2; + } + assert!(d.images["gray"].gray_source().unwrap().one_bit); + let (_, samples, warnings) = colorized_samples(&d, Level::Three); + assert_eq!(samples, vec![0b1000_0000]); + assert!(warnings.is_empty()); +} + +#[test] +fn one_source_with_two_spot_tints_writes_two_inks() { + let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; + let mut d = colorized_doc(vec![0, 255, 0], Some(first)); + let mut n = (*d.layers[0].children().unwrap()[0]).clone(); + n.id = d.alloc_id(); + n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + d.insert(d.default_layer(), 1, n).unwrap(); + let ps = page_of(&d, &opts(&d)); + assert!(ps.contains("VCsp0 setcolorspace 1 setcolor") && ps.contains("VCsp0 setcolorspace 0.5 setcolor"), "{ps}"); + assert_eq!(ps.matches("imagemask").count(), 2); +} + +#[test] +fn gray_colorized_ramp_scales_process_and_spot_inks_over_paper() { + for level in [Level::Two, Level::Three] { + let process = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let (ps, pixels, warnings) = colorized_samples(&process, level); + assert!(ps.contains("/DeviceRGB setcolorspace") && !ps.contains("imagemask")); + if level == Level::Three { + assert!(ps.contains("/ImageType 4") && ps.contains("/MaskColor [255 255 0 0 255 255]")); + assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 0, 255]); + assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]); + } else { + assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor")); + assert_eq!(pixels, vec![255, 0, 0, 255, 128, 128, 255, 255, 255]); + assert_eq!( + warnings, + vec![ + "partly transparent image pixels are written over white", + "transparent image pixels are written white at PostScript Level 2 (Level 3 masks them out)" + ] + ); + } + + let gray = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::gray(0.5)))); + let (ps, pixels, warnings) = colorized_samples(&gray, level); + assert!(ps.contains("/DeviceGray setcolorspace")); + assert_eq!(pixels, if level == Level::Three { vec![128, 192, 0] } else { vec![128, 192, 255] }); + assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three); + assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 }); + + let spot = colorized_doc(vec![0, 128, 255], Some(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 })); + let (ps, pixels, warnings) = colorized_samples(&spot, level); + assert!(ps.contains("/Separation (Ink) cvn") && ps.contains("VCsp0 setcolorspace")); + assert_eq!(dsc(&ps, "DocumentCustomColors").as_deref(), Some("(Ink)")); + assert_eq!(pixels, vec![128, 64, 0]); + assert_eq!(ps.contains("/MaskColor [0 0]"), level == Level::Three); + assert_eq!(warnings.len(), if level == Level::Three { 1 } else { 2 }); + + let mut cmyk = process.clone(); + cmyk.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let (ps, pixels, _) = colorized_samples(&cmyk, level); + assert!(ps.contains("/DeviceCMYK setcolorspace")); + assert_eq!(pixels.len(), 12); + assert_eq!(&pixels[8..], if level == Level::Three { &[255, 0, 255, 0][..] } else { &[0, 0, 0, 0][..] }); + } +} + +#[test] +fn continuous_colorized_coverage_without_clear_pixels_only_warns_for_midtones() { + let d = colorized_doc(vec![0, 128, 254], Some(Paint::solid(Color::rgb8(255, 0, 255)))); + for level in [Level::Two, Level::Three] { + let (ps, pixels, warnings) = colorized_samples(&d, level); + assert!(ps.contains("/ImageType 1") && !ps.contains("/MaskColor")); + assert_eq!(&pixels[..3], &[255, 0, 255]); + assert_eq!(warnings, vec!["partly transparent image pixels are written over white"]); + } + let d = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::rgb8(255, 0, 255)))); + let (ps, pixels, _) = colorized_samples(&d, Level::Three); + assert!(ps.contains("/MaskColor [255 255 0 0 255 255]")); + assert_eq!(&pixels[..3], &[255, 1, 255]); + assert_eq!(&pixels[6..], &[255, 0, 255]); +} + +#[test] +fn uncolorized_image_stays_on_original_eps_path() { + let d = colorized_doc(vec![0, 128, 255], None); + let ps = page_of(&d, &opts(&d)); + assert!(!ps.contains("imagemask") && ps.contains("/ImageType 1")); + let patterned = colorized_doc(vec![0, 128, 255], Some(Paint::Pattern { pattern: "missing".into(), xf: Affine::IDENTITY })); + assert_eq!(page_of(&patterned, &opts(&patterned)), ps); + let mut color = png_doc(); + let original = page_of(&color, &opts(&color)); + let id = color.layers[0].children().unwrap()[0].id; + color.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + assert_eq!(page_of(&color, &opts(&color)), original); +} + #[test] fn run_length_and_ascii85_round_trip() { let cycle: Vec = (0..=255u8).cycle().take(1000).collect(); diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 27be13e207..6ef3b64ddf 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -34,7 +34,7 @@ svgtypes = "0.16" skrifa = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } -resvg = { version = "0.45", default-features = false } +resvg = { version = "0.45", default-features = false, features = ["raster-images"] } # usvg as a reference viewer that lays text out in a font (text_layout.rs). usvg = { workspace = true, features = ["text"] } vectorcraft-testkit = { workspace = true } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 1da24959ca..b9cd372eae 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -107,11 +107,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: symbol_nest: 0, fonts: Vec::new(), shared_images: HashMap::new(), + colorized_counts: HashMap::new(), + colorized_hrefs: HashMap::new(), + shared_colorized: HashMap::new(), layer_nest: 0, non_latin1_names: false, foreign_ns: BTreeMap::new(), }; w.assign_name_ids(); + for layer in &doc.layers { + w.count_colorized_images(layer); + } // Page Isolated Blending / Page Knockout Group: the page content is one isolated group. let page_group = doc.page_isolate || doc.page_knockout; if page_group { @@ -216,6 +222,8 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: Output { svg: out, linked: w.linked, warnings: w.warnings, encoding } } +type ColorizedKey = (String, u32, u32, Option<[u8; 3]>); + struct Writer<'a> { doc: &'a Document, opts: &'a ExportOptions, @@ -268,6 +276,10 @@ struct Writer<'a> { /// Images written once in the defs and drawn with ``, by key and size: the pieces an /// envelope cuts a distorted image into share its pixels. shared_images: HashMap<(String, u32, u32), String>, + /// Counts and generated PNG hrefs for gray images, keyed by source, size and baked RGB. + colorized_counts: HashMap, + colorized_hrefs: HashMap, + shared_colorized: HashMap, /// Layers being written inside one another (more than one: a sublayer). layer_nest: usize, /// An emitted attribute name requires an encoding wider than Latin-1. diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 16722d9395..e88ad85098 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -117,6 +117,7 @@ fn pin_to_page(n: &mut Node, m: Affine) { /// What SVG Tiny 1.2 does without masks. const TINY_MASKS: &str = "SVG Tiny 1.2 has no masks: opacity masks are left out and knockout groups written as plain groups"; +pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; /// A region covering any artwork (mask and filter extents). const BIG: &str = "x=\"-100000\" y=\"-100000\" width=\"200000\" height=\"200000\""; @@ -565,6 +566,18 @@ impl Writer<'_> { } NodeKind::Text(t) => self.text_node(n, t), NodeKind::Image(im) => { + if let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() + && let Some(blob) = self.doc.image_blob(im) + && blob.gray_source().is_some() + { + self.colorized_image(n, im, *color, blob); + return; + } + if matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })) && self.doc.image_blob(im).is_none_or(|b| b.bytes.is_empty()) { + // Missing pixels cannot show the original file in place of a colorized image. + self.warn(UNDECODED); + return; + } let id = self.id_attr(n); let m = self.matrix(self.xf * im.xf); let mut props = css::transparency(n); diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index b21d45eb62..462387d70f 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -1,9 +1,9 @@ -use super::nodes::{MASK, doc_path}; +use super::nodes::{MASK, UNDECODED, doc_path}; use super::output::sanitize_id; use super::{ Affine, BezPath, BlendMode, Color, FillLayer, FillRule, GradientKind, GradientPaint, HashMap, ImageBlob, ImageMode, LineCap, LineJoin, - LinkedImage, Node, NodeKind, Paint, PathData, Point, Props, Rect, StrokeAlign, StrokeLayer, Writer, Written, base64_encode, blend_css, fmt_num, - stroke, xml_escape, + LinkedImage, Node, NodeKind, Paint, PathData, Point, Props, Rect, StrokeAlign, StrokeLayer, Writer, Written, base64_encode, blend_css, css, + fmt_num, stroke, xml_escape, }; /// Image `b` as SVG viewers show it: PNG, JPEG, GIF, WebP and SVG as they are, other formats (a @@ -38,6 +38,125 @@ pub(super) enum StrokePlan { } impl Writer<'_> { + pub(super) fn count_colorized_images(&mut self, art: &Node) { + art.walk(&mut |n| { + let NodeKind::Image(im) = &n.kind else { return }; + let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return }; + if self.doc.image_blob(im).is_none_or(|blob| blob.gray_source().is_none()) { + return; + } + let key = self.colorized_key(im, *color); + *self.colorized_counts.entry(key).or_default() += 1; + }); + } + + fn colorized_key(&self, im: &vectorcraft_doc::ImageObject, color: Color) -> super::ColorizedKey { + let rgb = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + (im.key.clone(), im.width, im.height, self.tiny().then_some(rgb)) + } + + /// Colorize the decoded gray pixels without changing the source blob. The white pixels of the + /// coverage image contribute their alpha to an alpha mask; Tiny uses the same alpha in RGBA. + pub(super) fn colorized_image(&mut self, n: &Node, im: &vectorcraft_doc::ImageObject, color: Color, blob: &ImageBlob) { + let key = self.colorized_key(im, color); + let rgb = color.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let href = if let Some(href) = self.colorized_hrefs.get(&key) { + href.clone() + } else { + let Some((width, height, coverage)) = blob.coverage() else { + self.warn(UNDECODED); + return; + }; + if u64::from(width) + .checked_mul(u64::from(height)) + .and_then(|pixels| pixels.checked_mul(4)) + .is_none_or(|bytes| bytes > vectorcraft_doc::MAX_RASTER_ALLOC) + { + self.warn(UNDECODED); + return; + } + let mut rgba = Vec::with_capacity(coverage.len().saturating_mul(4)); + for alpha in coverage { + rgba.extend_from_slice(&if self.tiny() { [rgb[0], rgb[1], rgb[2], alpha] } else { [255, 255, 255, alpha] }); + } + let Some(pixels) = image::RgbaImage::from_raw(width, height, rgba) else { + self.warn(UNDECODED); + return; + }; + let mut png = Vec::new(); + if pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { + self.warn(UNDECODED); + return; + } + let href = self.blob_href(&ImageBlob::png(png)); + self.colorized_hrefs.insert(key.clone(), href.clone()); + href + }; + let shared = if self.opts.images == ImageMode::Embed && self.colorized_counts.get(&key).is_some_and(|count| *count > 1) { + if let Some(id) = self.shared_colorized.get(&key) { + Some(id.clone()) + } else { + let id = self.fresh_id("colorize-image"); + self.def( + 0, + &format!( + "", + im.width, + im.height, + xml_escape(&href) + ), + ); + self.shared_colorized.insert(key, id.clone()); + Some(id) + } + } else { + None + }; + let id = self.id_attr(n); + let transform = self.matrix(self.xf * im.xf); + let outer = self.attrs(&css::transparency(n)); + let sampling = if n.extras().pixelated { " image-rendering=\"pixelated\"" } else { "" }; + if self.tiny() { + if let Some(shared) = shared { + self.line(&format!("")); + } else { + self.line(&format!( + "", + im.width, im.height, xml_escape(&href) + )); + } + return; + } + let mask = self.fresh_id("colorize-mask"); + let size = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)); + let b = (self.xf * im.xf).transform_rect_bbox(size).inflate(1.0, 1.0); + let (x, y, w, h) = (self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height())); + self.def(1, &format!("")); + if let Some(shared) = shared { + self.def(2, &format!("")); + } else { + self.def( + 2, + &format!( + "", + im.width, + im.height, + xml_escape(&href) + ), + ); + } + self.def(1, ""); + self.line(&format!("")); + self.depth += 1; + self.line(&format!("")); + self.depth += 1; + self.line(&format!("", im.width, im.height, color.to_hex())); + self.depth -= 1; + self.line(""); + self.depth -= 1; + self.line(""); + } + /// The `href` of image `im`: its file with [`ImageMode::Link`] (or when its pixels are /// missing), else its bytes. `None` when it has neither. pub(super) fn image_href(&mut self, im: &vectorcraft_doc::ImageObject) -> Option { @@ -52,10 +171,16 @@ impl Writer<'_> { /// Images drawn more than once in `art` (the pieces of a distorted image) go into the defs /// once; each piece then draws them with ``. pub(super) fn share_images(&mut self, art: &Node) { + self.count_colorized_images(art); // Each image's count and its first piece, which shows what they all show. let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new(); art.walk(&mut |c| { if let NodeKind::Image(im) = &c.kind { + if matches!(c.extras().colorize.as_deref(), Some(Paint::Solid { .. })) + && self.doc.image_blob(im).is_none_or(|b| b.gray_source().is_some()) + { + return; + } seen.entry((im.key.clone(), im.width, im.height)).or_insert_with(|| (0, (**im).clone())).0 += 1; } }); diff --git a/crates/svg/tests/it/colorized_images.rs b/crates/svg/tests/it/colorized_images.rs new file mode 100644 index 0000000000..d3590977f2 --- /dev/null +++ b/crates/svg/tests/it/colorized_images.rs @@ -0,0 +1,229 @@ +//! Colorized gray and bilevel image export, checked as pixels as well as markup. + +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind}; +use vectorcraft_geom::Affine; +use vectorcraft_svg::{ExportOptions, ImageMode, Profile, base64_encode, export_full}; + +fn bilevel() -> Vec { + let entries: [(u16, u16, u32); 9] = + [(256, 3, 2), (257, 3, 1), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 122), (277, 3, 1), (278, 3, 1), (279, 4, 1)]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&9u16.to_le_bytes()); + for (tag, kind, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.push(0b0100_0000); + out +} + +fn png(img: image::DynamicImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn document(bytes: Vec, paint: Option) -> Document { + let mut d = Document::new(80.0, 40.0); + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: true, spot: true }); + d.images.insert("source".into(), ImageBlob::new("image/tiff", bytes)); + let im = ImageObject { + key: "source".into(), + width: 2, + height: 1, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(20.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.extras_mut().pixelated = true; + n.extras_mut().colorize = paint.map(Box::new); + d.insert(d.default_layer(), 0, n).unwrap(); + d +} + +fn rendered(svg: &str) -> ([u8; 4], [u8; 4]) { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(80, 40).unwrap(); + pixmap.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pixmap.as_mut()); + let sample = |x| { + let p = pixmap.pixel(x, 15).unwrap().demultiply(); + [p.red(), p.green(), p.blue(), p.alpha()] + }; + (sample(15), sample(45)) +} + +fn samples(svg: &str, points: &[(u32, u32)]) -> Vec<[u8; 4]> { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(80, 40).unwrap(); + pixmap.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pixmap.as_mut()); + points + .iter() + .map(|&(x, y)| { + let p = pixmap.pixel(x, y).unwrap().demultiply(); + [p.red(), p.green(), p.blue(), p.alpha()] + }) + .collect() +} + +#[test] +fn repeated_colorized_source_shares_coverage_but_keeps_instance_paint() { + let mut d = document(bilevel(), Some(Paint::solid(Color::rgb8(255, 0, 0)))); + let first_id = d.layers[0].children().unwrap()[0].id; + if let NodeKind::Image(im) = &mut d.node_mut(first_id).unwrap().kind { + im.xf = Affine::translate((10.0, 10.0)) * Affine::scale(10.0); + } + for (i, color) in [(1, Color::rgb8(0, 0, 255)), (2, Color::rgb8(255, 0, 0))] { + let mut next = (*d.layers[0].children().unwrap()[0]).clone(); + next.id = d.alloc_id(); + next.extras_mut().colorize = Some(Box::new(Paint::solid(color))); + if let NodeKind::Image(im) = &mut next.kind { + im.xf = Affine::translate((10.0 + f64::from(i) * 25.0, 10.0)) * Affine::scale(10.0); + } + d.insert(d.default_layer(), i as usize, next).unwrap(); + } + for profile in [Profile::Svg11, Profile::Tiny12] { + let svg = export_full(&d, &ExportOptions { profile, artboard: Some(0), ..Default::default() }, None).svg; + let png_count = svg.matches("data:image/png;base64,").count(); + assert_eq!(png_count, if profile == Profile::Svg11 { 1 } else { 2 }, "{svg}"); + assert_eq!(svg.matches(""#.to_vec(); + for (bytes, mime) in [(svg_source, "image/svg+xml"), (vec![1, 2, 3], "image/tiff")] { + let mut d = document(bytes, None); + d.images.get_mut("source").unwrap().mime = mime.into(); + let before = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + let after = export_full(&d, &ExportOptions { artboard: Some(0), ..Default::default() }, None); + assert!(after.svg.contains(" positioned glyphs in points (before line breaking). +use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; @@ -8,6 +9,7 @@ use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; use harfrust::{Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; +use kurbo::Shape; use skrifa::MetadataProvider; use skrifa::charmap::Charmap; use skrifa::instance::Size; @@ -446,6 +448,217 @@ pub(crate) fn shape_range( { o.sort_by_key(|g| g.byte); } + if !feats.vertical { + optical_pairs(db, text, out.get_mut(output_start..).unwrap_or_default(), runs); + } +} + +/// Line segments of a glyph outline in font units, cached for the current shaping pass. +type Profile = Vec<(f64, f64, f64, f64)>; +type CachedProfile = (Profile, (f64, f64)); + +fn outline_profile(db: &FontDb, g: &SGlyph, cache: &mut HashMap<(u32, u32), Option>>) -> Option> { + let key = (g.face.id(), g.gid); + cache + .entry(key) + .or_insert_with(|| { + let path = db.outline(&g.face, g.gid); + let bounds = path.bounding_box(); + if path.elements().is_empty() + || path.elements().len() > 512 + || ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 100_000.0) + { + return None; + } + let mut lines = Vec::new(); + let mut previous = None; + let mut contour_start = None; + kurbo::flatten(path.iter(), 2.0, |el| match el { + kurbo::PathEl::MoveTo(p) => { + previous = Some(p); + contour_start = Some(p); + } + kurbo::PathEl::LineTo(p) => { + if let Some(a) = previous + && lines.len() < 8192 + { + lines.push((a.x, a.y, p.x, p.y)); + } + previous = Some(p); + } + kurbo::PathEl::ClosePath => { + if let Some((a, b)) = previous.zip(contour_start) + && lines.len() < 8192 + { + lines.push((a.x, a.y, b.x, b.y)); + } + previous = None; + contour_start = None; + } + _ => {} + }); + (!lines.is_empty() && lines.len() < 8192).then(|| Arc::new((lines, (bounds.y0, bounds.y1)))) + }) + .clone() +} + +/// The left and right ink edges where a horizontal slice crosses an outline. +fn profile_edges(lines: &[(f64, f64, f64, f64)], y: f64, sx: f64, sy: f64, dx: f64, dy: f64) -> Option<(f64, f64)> { + let mut left = f64::INFINITY; + let mut right = f64::NEG_INFINITY; + for &(x0, y0, x1, y1) in lines { + let (a, b) = (y0 * sy + dy, y1 * sy + dy); + if (a <= y && y < b) || (b <= y && y < a) { + let x = (x0 + (x1 - x0) * (y - a) / (b - a)) * sx + dx; + left = left.min(x); + right = right.max(x); + } + } + (left.is_finite() && right.is_finite()).then_some((left, right)) +} + +#[allow(clippy::too_many_arguments)] +fn profile_correction( + a: &[(f64, f64, f64, f64)], + b: &[(f64, f64, f64, f64)], + left: (f64, f64, f64, f64), + right: (f64, f64, f64, f64), + advance: f64, + em: f64, + upem: f64, + low: f64, + high: f64, +) -> Option { + if !low.is_finite() || !high.is_finite() || high <= low || !em.is_finite() || em <= 0.0 || !upem.is_finite() || upem <= 0.0 { + return None; + } + let mut gaps = Vec::new(); + for j in 0..24 { + let y = low + (high - low) * (f64::from(j) + 0.5) / 24.0; + if let (Some((_, ar)), Some((bl, _))) = + (profile_edges(a, y, left.0, left.1, left.2, left.3), profile_edges(b, y, right.0, right.1, right.2, right.3)) + { + gaps.push(advance + bl - ar); + } + } + if gaps.is_empty() { + return None; + } + gaps.sort_by(f64::total_cmp); + let gap = gaps.get(gaps.len() / 2).copied().unwrap_or(0.0); + let unit = em / upem; + let correction = ((0.08 * em - gap).clamp(-0.25 * em, 0.25 * em) / unit).round() * unit; + let correction = correction.clamp(-0.25 * em, 0.25 * em); + correction.is_finite().then_some(correction) +} + +/// Move each Optical pair toward an ink gap of 0.08 em, at 24 overlapping vertical slices. +/// The median avoids a single narrow tip deciding the entire pair. Corrections are rounded to +/// one font unit and limited to 1/4 em in either direction. Missing ink gives zero correction. +fn optical_pairs(db: &FontDb, text: &str, glyphs: &mut [SGlyph], runs: &[(Range, &CharStyle)]) { + let mut cache = HashMap::new(); + let mut corrections: HashMap<[u64; 15], Option> = HashMap::new(); + let shaped_advances: Vec = glyphs.iter().map(|g| g.adv).collect(); + for i in 0..glyphs.len().saturating_sub(1) { + let Some((a, b)) = glyphs.get(i).zip(glyphs.get(i + 1)) else { continue }; + if a.level != b.level { + continue; + } + let Some(owner) = runs.get(a.run).map(|(_, s)| *s) else { continue }; + let invisible = |ch: char| matches!(ch, SOFT_HYPHEN | '\u{2028}') || ch.is_control(); + if !owner.optical_kerning + || a.byte == b.byte + || invisible(a.ch) + || invisible(b.ch) + || text.get(a.byte..b.byte).is_some_and(|between| between.chars().skip(1).any(invisible)) + || a.rotation != 0.0 + || b.rotation != 0.0 + { + continue; + } + if owner.kerning.is_some() { + continue; + } + let mut start = i; + while start > 0 && glyphs.get(start - 1).is_some_and(|g| g.byte == a.byte) { + start -= 1; + } + let mut end = i + 1; + while end + 1 < glyphs.len() && glyphs[end + 1].byte == b.byte { + end += 1; + } + // A mark may precede its base inside either direction's shaped cluster. + let advance = |k: usize| shaped_advances.get(k).copied().unwrap_or(0.0); + let first_base = glyphs[start..=i] + .iter() + .enumerate() + .max_by(|(a, _), (b, _)| advance(start + *a).total_cmp(&advance(start + *b))) + .map_or(start, |(offset, _)| start + offset); + let second_base = glyphs[i + 1..=end] + .iter() + .enumerate() + .max_by(|(a, _), (b, _)| advance(i + 1 + *a).total_cmp(&advance(i + 1 + *b))) + .map_or(i + 1, |(offset, _)| i + 1 + offset); + let (left_index, right_index, target, cluster_start, cluster_end) = + if a.level.is_rtl() { (second_base, first_base, end, i + 1, end) } else { (first_base, second_base, i, start, i) }; + let (left, right) = (&glyphs[left_index], &glyphs[right_index]); + if left.byte == right.byte + || left.is_space() + || right.is_space() + || is_mark(right.ch) + || left.inline.is_some() + || right.inline.is_some() + || left.ch == '\n' + || right.ch == '\n' + { + continue; + } + let left_y = left.dy - left.bshift; + let right_y = right.dy - right.bshift; + let Some(left_style) = runs.get(left.run).map(|(_, s)| *s) else { continue }; + let em = left.sx * left.face.upem / (left_style.h_scale / 100.0); + let tracking = left_style.tracking / 1000.0 * em; + let manual = left_style.kerning.unwrap_or(0.0) / 1000.0 * em; + let advance = glyphs[cluster_start..=cluster_end].iter().map(|g| g.adv).sum::() - tracking - manual; + let key = [ + u64::from(left.face.id()), + u64::from(left.gid), + u64::from(right.face.id()), + u64::from(right.gid), + left.sx.to_bits(), + left.sy.to_bits(), + left.dx.to_bits(), + left_y.to_bits(), + right.sx.to_bits(), + right.sy.to_bits(), + right.dx.to_bits(), + right_y.to_bits(), + advance.to_bits(), + em.to_bits(), + left.face.upem.to_bits(), + ]; + let correction = *corrections.entry(key).or_insert_with(|| { + let (Some(a), Some(b)) = (outline_profile(db, left, &mut cache), outline_profile(db, right, &mut cache)) else { return None }; + let low = (a.1.0 * left.sy + left_y).max(b.1.0 * right.sy + right_y); + let high = (a.1.1 * left.sy + left_y).min(b.1.1 * right.sy + right_y); + profile_correction( + &a.0, + &b.0, + (left.sx, left.sy, left.dx, left_y), + (right.sx, right.sy, right.dx, right_y), + advance, + em, + left.face.upem, + low, + high, + ) + }); + if let (Some(correction), Some(glyph)) = (correction, glyphs.get_mut(target)) + && !invisible(glyph.ch) + { + glyph.adv += correction; + } + } } /// Index in the original run list containing `byte`, limited to one coalesced shaping span. @@ -474,6 +687,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { leading: _, tracking, kerning: _, + optical_kerning: _, baseline_shift: _, h_scale, v_scale, @@ -696,6 +910,15 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe }; let manual = |byte: usize| run_at(byte).1.kerning.is_some(); let mixed_kerning = boundaries().any(|b| manual(b) != manual(range.start)); + let optical = |byte: usize| run_at(byte).1.optical_kerning; + let mode_boundaries: Vec = boundaries().filter(|&b| !feats.vertical && optical(b - 1) && !optical(b)).collect(); + if !mode_boundaries.is_empty() { + return shape_apart(mode_boundaries, out); + } + let manual_ends: Vec = boundaries().filter(|&b| manual(b - 1) && !manual(b)).collect(); + if !manual_ends.is_empty() { + return shape_apart(manual_ends, out); + } // Shape the segment as if all of it were in `st`, with the features `more` on top. let shape_in = |st: &CharStyle, more: &[Feature]| { @@ -793,17 +1016,43 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe } shaped }; - let Shaped { raw, proportional, vpal } = if mixed_kerning { + let first_optical = if optical(range.start) { Some(range.start) } else { boundaries().find(|&b| optical(b)) }; + let Shaped { raw, proportional, vpal } = if let Some(first) = first_optical.filter(|_| !feats.vertical) { + // The pair entering Optical keeps the left character's font kerning. Subsequent + // Optical pairs use outline spacing, so font pair features stop at its second character. + let optical_off = if first == range.start { + first + } else { + text.get(first..range.end).and_then(|s| s.chars().next()).map_or(range.end, |c| first + c.len_utf8()) + }; + let first_manual = if manual(range.start) { Some(range.start) } else { boundaries().find(|&b| manual(b)) }; + if let Some(start) = first_manual.filter(|&b| b > range.start) + && upper + && first_char(start).to_uppercase().nth(1).is_some() + { + return shape_apart(vec![start], out); + } + let manual_off = first_manual.map_or(range.end, |start| { + if start == range.start { + start + } else { + text.get(start..range.end).and_then(|s| s.chars().next()).map_or(range.end, |c| start + c.len_utf8()) + } + }); + let off = optical_off.min(manual_off); + let more: Vec = [b"kern", b"apkn", b"vkrn", b"vapk"] + .into_iter() + .filter(|_| off < range.end) + .map(|t| Feature::new(Tag::new(t), 0, off..range.end)) + .collect(); + shape_in(&CharStyle { kerning: None, ..run_at(range.start).1.clone() }, &more) + } else if mixed_kerning { // A font's kerning pair applies after a character with automatic kerning and not after one // with manual kerning. The segment is shaped apart where manual kerning ends, so each piece // is text with automatic kerning followed by text with manual kerning. A piece is shaped // with the font's kerning on, and off (`kern`, and the `apkn`, `vkrn` and `vapk` that // `OtFeatures` turns off with it) from the second character with manual kerning on: a // pair is applied only when both of its glyphs have the feature on. - let ends: Vec = boundaries().filter(|&b| manual(b - 1) && !manual(b)).collect(); - if !ends.is_empty() { - return shape_apart(ends, out); - } let first = boundaries().find(|&b| manual(b)).unwrap_or(range.end); // A first character with manual kerning that All Caps or Small Caps sets as several letters // (ß as SS) gives them one cluster, which a feature range cannot split, so the font's @@ -879,3 +1128,27 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe }); } } + +#[cfg(test)] +mod optical_tests { + use super::*; + + fn box_profile(left: f64, right: f64) -> Profile { + vec![(left, 0.0, left, 100.0), (right, 0.0, right, 100.0)] + } + + #[test] + fn optical_side_profiles_tighten_loosen_and_stay_bounded() { + let a = box_profile(0.0, 80.0); + let b = box_profile(0.0, 20.0); + let place = (1.0, 1.0, 0.0, 0.0); + let tight = profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); + let loose = profile_correction(&a, &b, place, place, 60.0, 100.0, 1000.0, 0.0, 100.0).unwrap(); + assert_eq!(tight, -25.0); + assert_eq!(loose, 25.0); + assert_eq!(profile_correction(&a, &b, place, place, 88.0, 100.0, 1000.0, 0.0, 100.0), Some(0.0)); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), Some(tight)); + assert_eq!(profile_correction(&a, &b, place, place, 120.0, 100.0, 1000.0, 100.0, 100.0), None); + assert_eq!(profile_correction(&[], &b, place, place, 120.0, 100.0, 1000.0, 0.0, 100.0), None); + } +} diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index f3619679ff..817f1689f4 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -412,6 +412,81 @@ pub fn lam_alef_font(feature: &[u8; 4]) -> Option> { /// The family of [`pair_kerning_font`]. pub const PAIR_KERNING_FAMILY: &str = "Pairtest Sans"; +/// The family of [`no_pair_kerning_font`]. +pub const NO_PAIR_KERNING_FAMILY: &str = "No Pairtest Sans"; + +/// A font with the bundled Source Sans 3 outlines and no `GPOS` or `kern` table. +pub fn no_pair_kerning_font() -> Option> { + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let family = NO_PAIR_KERNING_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "No Pairtest Sans Regular"), (6, "NoPairtestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !matches!(tag, t if t == Tag::new(b"name") || t == Tag::new(b"GPOS") || t == Tag::new(b"kern")) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`right_to_left_optical_font`]. +pub const RIGHT_TO_LEFT_OPTICAL_FAMILY: &str = "Right-to-left Profile Sans"; + +/// Two Hebrew characters mapped to the bundled Source Sans 3 A and V outlines. +pub fn right_to_left_optical_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mapping = [('א', 'A'), ('ב', 'V')]; + let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = RIGHT_TO_LEFT_OPTICAL_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Right-to-left Profile Sans Regular"), (6, "RtlProfileSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GPOS") && tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`soft_hyphen_outline_font`]. +pub const SOFT_HYPHEN_OUTLINE_FAMILY: &str = "Soft Hyphen Profile Sans"; + +/// A face that maps the invisible soft hyphen to the bundled hyphen outline. +pub fn soft_hyphen_outline_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mappings = [('A', 'A'), ('V', 'V'), ('-', '-'), ('\u{00AD}', '-')] + .into_iter() + .map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = SOFT_HYPHEN_OUTLINE_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Soft Hyphen Profile Sans Regular"), (6, "SoftHyphenProfileSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GPOS") && tag != Tag::new(b"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The bundled Source Sans 3 Regular as family [`PAIR_KERNING_FAMILY`], its `GPOS` replaced by two /// `kern` pairs, A followed by V and S followed by S: each takes 60 units off the first glyph's /// advance (the pair's first value record) and moves the second 100 units left (its second). diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 345340b52e..105c1b424e 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -18,6 +18,267 @@ fn run(text: &str, size: f64) -> TextRun { TextRun { text: text.into(), style: style(size), inline: None } } +#[test] +fn optical_pairs_cross_paint_runs_and_manual_and_tracking_are_independent() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut t = TextObject::point(Point::ZERO, "III", st); + let advance = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.advance).collect::>(); + let optical = advance(&t); + let mut plain = t.clone(); + plain.runs[0].style.kerning = Some(0.0); + let unkerned = advance(&plain); + assert!((optical[0] - unkerned[0]).abs() > 0.1, "Optical changes the monospaced pair"); + edit::style_range(&mut t.runs, 1, 2, |s| s.fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb(1.0, 0.0, 0.0))); + let painted = advance(&t); + assert!((painted[0] - optical[0]).abs() < 0.01, "paint does not interrupt Optical"); + edit::style_range(&mut t.runs, 0, 1, |s| s.kerning = Some(0.0)); + let manual = advance(&t); + assert!((manual[0] - unkerned[0]).abs() < 0.01); + assert!((manual[1] - optical[1]).abs() < 0.01, "the next pair remains Optical"); + edit::style_range(&mut t.runs, 0, 3, |s| s.tracking = 100.0); + let tracked = advance(&t); + assert!((tracked[0] - manual[0] - 10.0).abs() < 0.01); + assert!((tracked[1] - manual[1] - 10.0).abs() < 0.01); + + for text in ["I I", "I\u{301}"] { + let sample = TextObject::point(Point::ZERO, text, CharStyle { kerning: None, ..t.runs[0].style.clone() }); + let mut zero = sample.clone(); + zero.runs[0].style.kerning = Some(0.0); + assert_eq!(advance(&sample), advance(&zero), "spaces and marks inside a cluster have no Optical correction"); + } + let mut vertical = TextObject::point(Point::ZERO, "II", CharStyle { kerning: None, ..t.runs[0].style.clone() }); + vertical.vertical = true; + let mut vertical_zero = vertical.clone(); + vertical_zero.runs[0].style.kerning = Some(0.0); + assert_eq!(advance(&vertical), advance(&vertical_zero), "vertical type keeps a neutral correction"); + let rtl = TextObject::point(Point::ZERO, "אב", CharStyle { kerning: None, ..t.runs[0].style.clone() }); + let rtl_advances = advance(&rtl); + assert!(rtl_advances.len() >= 2 && rtl_advances.iter().all(|v| v.is_finite())); + let mut rtl_zero = rtl.clone(); + rtl_zero.runs[0].style.kerning = Some(0.0); + assert!((rtl_advances[1] - advance(&rtl_zero)[1]).abs() <= 25.0, "right-to-left Optical corrections remain bounded"); + let mut rtl_manual = rtl.clone(); + edit::style_range(&mut rtl_manual.runs, 0, 2, |s| s.kerning = Some(200.0)); + let mut rtl_pair_zero = rtl.clone(); + edit::style_range(&mut rtl_pair_zero.runs, 0, 2, |s| s.kerning = Some(0.0)); + let pair_advance = |t: &TextObject| layout(db(), t).glyphs.iter().find(|g| g.byte == 0).map(|g| g.advance).unwrap(); + assert!((pair_advance(&rtl_pair_zero) - pair_advance(&rtl_zero)).abs() < 0.01, "manual zero replaces the right-to-left Optical correction"); + assert!((pair_advance(&rtl_manual) - pair_advance(&rtl_pair_zero) - 20.0).abs() < 0.01, "manual spacing changes the adjacent right-to-left pair"); +} + +#[test] +fn optical_pair_skips_an_invisible_soft_hyphen_with_an_outline() { + use crate::test_fonts::{SOFT_HYPHEN_OUTLINE_FAMILY, soft_hyphen_outline_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(soft_hyphen_outline_font().unwrap()), 1); + let style = CharStyle { font_family: SOFT_HYPHEN_OUTLINE_FAMILY.into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let face = db.style_face(&style).unwrap(); + assert_ne!(face.glyph_for('\u{00AD}'), 0); + assert_eq!(face.glyph_for('\u{00AD}'), face.glyph_for('-')); + let paired = layout(&db, &TextObject::point(Point::ZERO, "AV", style.clone())); + let separated = layout(&db, &TextObject::point(Point::ZERO, "A\u{00AD}V", style.clone())); + let mut manual = style; + manual.kerning = Some(0.0); + let plain = layout(&db, &TextObject::point(Point::ZERO, "A\u{00AD}V", manual)); + + assert!((paired.glyphs[0].advance - plain.glyphs[0].advance).abs() > 0.1, "A-V has an Optical correction"); + // A keeps its uncorrected advance because neither pair across the invisible glyph is measured. + assert!((separated.glyphs[0].advance - plain.glyphs[0].advance).abs() < 0.01); + assert!(separated.glyphs.iter().filter(|g| g.byte == 1).all(|g| g.advance == 0.0), "the soft hyphen remains zero width if emitted"); + let v = |lay: &TextLayout| lay.glyphs.iter().find(|g| g.byte == 3).unwrap().origin.x; + assert!((v(&separated) - v(&plain)).abs() < 0.01, "the soft hyphen adds no spacing"); +} + +#[test] +fn optical_pair_after_separate_combining_mark_uses_base_outline() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let advances = |text: &str, manual: bool| { + let mut style = st.clone(); + if manual { + style.kerning = Some(0.0); + } + layout(db(), &TextObject::point(Point::ZERO, text, style)).glyphs.iter().map(|g| (g.byte, g.advance)).collect::>() + }; + let plain = advances("II", false); + let plain_zero = advances("II", true); + let accented = advances("I\u{30d}I", false); + let accented_zero = advances("I\u{30d}I", true); + assert_eq!(accented.len(), 3, "the accent has its own glyph"); + assert_eq!(accented[0].0, accented[1].0, "the base and mark share a cluster"); + assert!((accented[0].1 - accented_zero[0].1).abs() < 0.01, "the base keeps its advance"); + let correction = accented[1].1 - accented_zero[1].1; + assert!((correction - (plain[0].1 - plain_zero[0].1)).abs() < 0.01, "the marked cluster uses the base outline"); + assert!(correction.abs() > 0.1, "Optical adjusts the pair after the accent"); +} + +#[test] +fn optical_pair_after_rtl_separate_mark_uses_base_outline() { + let st = CharStyle { font_family: "Noto Sans Arabic".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let shaped = |text: &str, manual: bool| { + let mut style = st.clone(); + if manual { + style.kerning = Some(0.0); + } + layout(db(), &TextObject::point(Point::ZERO, text, style)).glyphs.iter().map(|g| (g.byte, g.advance)).collect::>() + }; + let plain = shaped("بب", false); + let plain_zero = shaped("بب", true); + let marked = shaped("بَب", false); + let marked_zero = shaped("بَب", true); + let marked_cluster = marked.iter().filter(|g| g.0 == 0).collect::>(); + assert_eq!(marked_cluster.len(), plain.iter().filter(|g| g.0 == 0).count() + 1, "the mark has its own glyph in the base cluster"); + assert_eq!(marked_cluster.first().unwrap().1, 0.0, "the cluster starts with a nonspacing glyph"); + assert!(marked_cluster.last().unwrap().1 > 0.0, "the base follows the mark"); + let correction = marked.iter().filter(|g| g.0 == 4).map(|g| g.1).sum::() - marked_zero.iter().filter(|g| g.0 == 4).map(|g| g.1).sum::(); + let plain_correction = + plain.iter().filter(|g| g.0 == 2).map(|g| g.1).sum::() - plain_zero.iter().filter(|g| g.0 == 2).map(|g| g.1).sum::(); + assert!(plain_correction.abs() > 0.1, "Optical adjusts the unmarked pair"); + assert!((correction - plain_correction).abs() < 0.01, "the marked cluster uses the base outline"); +} + +#[test] +fn recurring_optical_pairs_have_equal_corrections() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let text = "II".repeat(50); + let optical = layout(db(), &TextObject::point(Point::ZERO, &text, st.clone())).glyphs.iter().map(|g| g.advance).collect::>(); + let zero = layout(db(), &TextObject::point(Point::ZERO, &text, CharStyle { kerning: Some(0.0), ..st })) + .glyphs + .iter() + .map(|g| g.advance) + .collect::>(); + assert_eq!(optical.len(), zero.len()); + let correction = optical[0] - zero[0]; + assert!(correction.abs() > 0.1); + for i in 1..optical.len() - 1 { + assert_eq!(optical[i] - zero[i], correction, "pair {i} has the same correction"); + } +} + +#[test] +fn metrics_pair_survives_transition_to_optical() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVV", st); + let advances = |text: &TextObject| layout(db(), text).glyphs.iter().map(|g| g.advance).collect::>(); + let metrics = advances(&text); + let mut unkerned = text.clone(); + unkerned.runs[0].style.kerning = Some(0.0); + assert!((metrics[0] - advances(&unkerned)[0]).abs() > 0.1, "the font supplies an AV pair"); + edit::style_range(&mut text.runs, 1, 3, |s| s.optical_kerning = true); + let mixed = advances(&text); + assert!((mixed[0] - metrics[0]).abs() < 0.01, "the metrics AV pair crosses the mode change"); + let mut optical = TextObject::point(Point::ZERO, "VV", text.runs[1].style.clone()); + let optical_pair = advances(&optical)[0]; + optical.runs[0].style.kerning = Some(0.0); + assert!((mixed[1] - optical_pair).abs() < 0.01, "the first Optical V keeps its next pair"); + assert!((mixed[1] - advances(&optical)[0]).abs() > 0.1, "Optical corrects the next pair"); +} + +#[test] +fn manual_pair_before_optical_does_not_gain_font_kerning() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVA", st); + edit::style_range(&mut text.runs, 1, 2, |s| s.kerning = Some(0.0)); + edit::style_range(&mut text.runs, 2, 3, |s| s.optical_kerning = true); + let mixed = layout(db(), &text).glyphs[1].advance; + let mut unkerned = TextObject::point(Point::ZERO, "VA", text.runs[1].style.clone()); + unkerned.runs[0].style.kerning = Some(0.0); + let manual = layout(db(), &unkerned).glyphs[0].advance; + assert!((mixed - manual).abs() < 0.01, "manual V keeps its unkerned pair with Optical A"); +} + +#[test] +fn optical_pair_uses_drawn_baseline() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "II", st); + let first = |text: &TextObject| layout(db(), text).glyphs[0].advance; + let normal = first(&text); + edit::style_range(&mut text.runs, 1, 2, |s| s.baseline_shift = 80.0); + let shifted = first(&text); + assert!((shifted - normal).abs() > 0.1, "a displaced outline changes the Optical correction"); +} + +#[test] +fn optical_pair_skips_rotated_glyphs() { + let st = CharStyle { font_family: "JetBrains Mono".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "II", st); + let first = |text: &TextObject| layout(db(), text).glyphs[0].advance; + let unrotated = first(&text); + let mut plain = text.clone(); + plain.runs[0].style.kerning = Some(0.0); + assert!((unrotated - first(&plain)).abs() > 0.1, "the unrotated pair has an Optical correction"); + edit::style_range(&mut text.runs, 1, 2, |s| s.rotation = 20.0); + let rotated = first(&text); + let mut manual_zero = text.clone(); + edit::style_range(&mut manual_zero.runs, 0, 1, |s| s.kerning = Some(0.0)); + assert!((rotated - first(&manual_zero)).abs() < 0.01, "rotated pairs keep their uncorrected advance"); +} + +#[test] +fn optical_shaping_keeps_manual_value_on_first_run() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, optical_kerning: true, kerning: Some(0.0), ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AVA", st); + let zero = layout(db(), &text).glyphs.iter().map(|g| g.advance).collect::>(); + edit::style_range(&mut text.runs, 0, 1, |s| s.kerning = Some(120.0)); + let manual = layout(db(), &text).glyphs.iter().map(|g| g.advance).collect::>(); + assert!((manual[0] - zero[0] - 12.0).abs() < 0.01, "the first run adds its manual value"); + assert!((manual[1] - zero[1]).abs() < 0.01, "the following run keeps its advance"); +} + +#[test] +fn ordinary_and_vertical_segments_keep_their_spacing() { + let st = CharStyle { font_family: "Source Sans 3".into(), size: 100.0, kerning: Some(100.0), ..CharStyle::default() }; + let plain = TextObject::point(Point::ZERO, "AVA", st); + let advances = |text: &TextObject| layout(db(), text).glyphs.iter().map(|g| g.advance).collect::>(); + let expected = advances(&plain); + let mut split = plain.clone(); + edit::style_range(&mut split.runs, 1, 2, |s| s.fill = vectorcraft_doc::color::Paint::solid(vectorcraft_doc::color::Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(advances(&split), expected, "a non-Optical segment keeps the same spacing across runs"); + + let mut vertical = plain; + vertical.vertical = true; + let expected = advances(&vertical); + edit::style_range(&mut vertical.runs, 0, 1, |s| s.kerning = Some(120.0)); + let manual = advances(&vertical); + assert!((manual[0] - expected[0] - 2.0).abs() < 0.01, "vertical manual spacing changes only its own advance"); + edit::style_range(&mut vertical.runs, 0, 3, |s| s.optical_kerning = true); + assert_eq!(advances(&vertical), manual, "vertical type keeps its spacing with Optical selected"); +} + +#[test] +fn optical_spacing_works_without_font_pair_tables() { + use crate::test_fonts::{NO_PAIR_KERNING_FAMILY, no_pair_kerning_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(no_pair_kerning_font().unwrap()), 1); + let st = CharStyle { font_family: NO_PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let mut text = TextObject::point(Point::ZERO, "AV", st); + let metrics = layout(&db, &text).glyphs[0].advance; + text.runs[0].style.kerning = Some(0.0); + let manual_zero = layout(&db, &text).glyphs[0].advance; + assert!((metrics - manual_zero).abs() < 0.01, "the font has no automatic pair correction"); + text.runs[0].style.kerning = None; + text.runs[0].style.optical_kerning = true; + let optical = layout(&db, &text).glyphs[0].advance; + assert!((optical - manual_zero).abs() > 0.1, "Optical uses outlines without a pair table"); +} + +#[test] +fn manual_pair_positions_match_under_auto_and_optical_in_both_directions() { + use crate::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; + + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(right_to_left_optical_font().unwrap()), 1); + for (letters, family) in [("AV", "Source Sans 3"), ("אב", RIGHT_TO_LEFT_OPTICAL_FAMILY)] { + let mut text = TextObject::point(Point::ZERO, letters, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() }); + edit::style_range(&mut text.runs, 0, letters.chars().next().unwrap().len_utf8(), |s| s.kerning = Some(200.0)); + let positions = |text: &TextObject| layout(&db, text).glyphs.iter().map(|g| (g.byte, g.origin, g.advance)).collect::>(); + let auto = positions(&text); + edit::style_range(&mut text.runs, 0, letters.len(), |s| s.optical_kerning = true); + assert_eq!(positions(&text), auto, "{letters}: manual pair has the same positions in both modes"); + } +} + fn area_path(text: &str, st: CharStyle, frame: &BezPath, justify: Justify) -> TextObject { let mut t = TextObject::point(Point::ZERO, text, st); t.kind = TextKind::Area { frame: PathData::from_bezpath(frame) }; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index d69b5df292..a2206df5eb 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -719,5 +719,29 @@ fn proportional_metrics_kern_the_glyphs_they_respace() { }; let (auto, manual) = (lay(true, None), lay(true, Some(0.0))); assert!(auto.iter().zip(&manual).any(|(a, b)| (a - b).abs() > 0.01), "kerned: {auto:?} {manual:?}"); + let optical = { + let s = CharStyle { font_family: "Noto Sans CJK SC".into(), optical_kerning: true, ..st(true, None) }; + layout(&db, &vertical_styled("「カタカナ」とトップ、ヤッホー。", s)).glyphs.iter().map(|g| g.advance).collect::>() + }; + assert!(auto.iter().zip(&optical).all(|(a, b)| (a - b).abs() < 0.01), "vertical Optical uses font metrics: {auto:?} {optical:?}"); assert!(lay(false, None).iter().all(|a| (a - 20.0).abs() < 0.01), "off: an em each, as before"); } + +#[test] +fn vertical_optical_to_auto_keeps_the_fonts_pair() { + use crate::test_fonts::{PAIR_KERNING_FAMILY, pair_kerning_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(pair_kerning_font().unwrap()); + let style = CharStyle { font_family: PAIR_KERNING_FAMILY.into(), size: 100.0, ..CharStyle::default() }; + let positions = + |t: &TextObject| layout(&db, t).glyphs.iter().map(|g| (g.advance, g.origin, g.xf.as_coeffs()[4], g.xf.as_coeffs()[5])).collect::>(); + let auto = vertical_styled("AV", style.clone()); + let mut mixed = auto.clone(); + edit::style_range(&mut mixed.runs, 0, 1, |s| s.optical_kerning = true); + let mut unkerned = auto.clone(); + edit::style_range(&mut unkerned.runs, 0, 1, |s| s.kerning = Some(0.0)); + let expected = positions(&auto); + assert_eq!(expected.len(), 2); + assert_ne!(expected, positions(&unkerned), "the font's A-V pair changes vertical positions"); + assert_eq!(positions(&mixed), expected, "vertical Optical keeps the A-V font pair across the style boundary"); +} diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 1a0f8e6335..042a6f5174 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -12,6 +12,7 @@ workspace = true vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } +vectorcraft-brush = { workspace = true } vectorcraft-pathops = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-text = { workspace = true } diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index 984b272e6e..fb292ea37c 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -7,7 +7,9 @@ //! which member is drawn on top there. //! //! The Intertwine tool is what `object.intertwine.make` and `object.intertwine.edit` leave the -//! canvas in: hovering highlights the overlap area under the pointer, a click arranges it, a drag +//! canvas in: hovering highlights the overlap area under the pointer (where three or more members +//! overlap, the outline of the member nearest to the pointer, which the right-click menu +//! arranges: [`menu_target`]), a click arranges it, a drag //! draws a path around overlap areas (Shift: a rectangle) and arranges every one inside it. //! Esc or Enter goes back to the tool chosen before. Behaviour: //! . @@ -16,7 +18,7 @@ use std::sync::Arc; use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_doc::intertwine::over_area; +use vectorcraft_doc::intertwine::tier_at; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind}; use vectorcraft_effects as effects; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes}; @@ -101,8 +103,18 @@ pub struct Face { /// Every overlap area of `children`. pub fn faces(children: &[Arc]) -> Vec { + faces_of(&painted_areas(children)) +} + +/// What each of `children` paints ([`painted_area`]), by child index. +pub fn painted_areas(children: &[Arc]) -> Vec> { + children.iter().map(|c| painted_area(c)).collect() +} + +/// Every overlap area of the members that paint `areas` ([`painted_areas`]). +pub fn faces_of(areas: &[Option]) -> Vec { let shapes: Vec = - children.iter().enumerate().filter_map(|(i, c)| Some(po::Shape::new(painted_area(c)?, FillRule::NonZero, i as u64))).collect(); + areas.iter().enumerate().filter_map(|(i, a)| Some(po::Shape::new(a.clone()?, FillRule::NonZero, i as u64))).collect(); let key = |k: usize| shapes.get(k).map(|s| s.key as usize); po::regions(&shapes) .into_iter() @@ -124,15 +136,37 @@ pub fn faces_in(faces: &[Face], lasso: &PathData) -> Vec { faces.iter().filter(|f| contains(lasso, f.inside)).cloned().collect() } -/// The members of `face` in the order they are drawn there, bottom first: those drawn in their -/// own order, then those drawn over the others there, each run in the group's order. +/// The members of `face` in the order they are drawn there, bottom first: by their tier there +/// ([`tier_at`]), and members of one tier in the group's order. pub fn drawn_order(children: &[Arc], face: &Face) -> Vec { - let over = |i: &usize| children.get(*i).and_then(|c| over_area(c)).is_some_and(|a| contains(a, face.inside)); + let tier = |i: usize| children.get(i).map_or(0, |c| tier_at(c, face.inside)); let mut order = face.members.clone(); - order.sort_by_key(|i| (over(i), *i)); + order.sort_by_cached_key(|i| (tier(*i), *i)); order } +/// The fewest members an overlap area needs for the right-click menu that arranges one of them. +pub const MENU_MEMBERS: usize = 3; + +/// The member of `face` whose outline (what it paints, `areas` from [`painted_areas`]) is nearest +/// to `p`. +pub fn nearest_member(areas: &[Option], face: &Face, p: Point) -> Option { + let dist = |i: usize| areas.get(i).and_then(Option::as_ref).map(|a| vectorcraft_geom::hit::distance_to_outline(&a.to_bezpath(), p)); + face.members.iter().filter_map(|i| Some((*i, dist(*i)?))).filter(|(_, d)| d.is_finite()).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) +} + +/// What a right-click at `p` arranges with the Intertwine tool: the Intertwine group of the +/// selection, and the member nearest to `p` (by id) in the overlap area under `p`, when +/// [`MENU_MEMBERS`] or more members overlap there. +pub fn menu_target(doc: &Document, selected: &[NodeId], p: Point) -> Option<(NodeId, NodeId)> { + let g = selected_group(doc, selected)?; + let children = doc.node(g)?.children()?; + let areas = painted_areas(children); + let face = face_at(&faces_of(&areas), p).filter(|f| f.members.len() >= MENU_MEMBERS)?; + let m = nearest_member(&areas, &face, p)?; + Some((g, children.get(m)?.id)) +} + /// The Intertwine group the selection is in, or is (the innermost one around the first selected /// object that is in one). pub fn selected_group(doc: &Document, selected: &[NodeId]) -> Option { @@ -149,6 +183,8 @@ pub fn is_intertwine(n: &Node) -> bool { struct Found { revision: (u64, u64), group: NodeId, + /// What each member paints, by child index. + areas: Arc>>, faces: Arc>, } @@ -159,7 +195,8 @@ pub struct IntertwineTool { prev: Option, /// The overlap areas of the group, for the document revision they were found in. cache: Option, - /// The overlap area under the pointer. + /// What the pointer highlights: the overlap area under it, or where [`MENU_MEMBERS`] or more + /// members overlap, the outline of the member nearest to it. hover: Option, /// A drag's points (document space); the first is where it started. points: Vec, @@ -170,17 +207,31 @@ pub struct IntertwineTool { impl IntertwineTool { fn faces(&mut self, cx: &ToolContext) -> Option<(NodeId, Arc>)> { + self.found(cx).map(|c| (c.group, c.faces.clone())) + } + + /// The overlap areas of the selection's group, found again when the document changed. + fn found(&mut self, cx: &ToolContext) -> Option<&Found> { let g = selected_group(cx.doc, &cx.selection.objects)?; - if let Some(c) = &self.cache - && c.revision == cx.revision - && c.group == g - { - return Some((g, c.faces.clone())); + if !self.cache.as_ref().is_some_and(|c| c.revision == cx.revision && c.group == g) { + let children = cx.doc.node(g)?.children()?; + let areas = painted_areas(children); + let faces = Arc::new(faces_of(&areas)); + self.cache = Some(Found { revision: cx.revision, group: g, areas: Arc::new(areas), faces }); } - let children = cx.doc.node(g)?.children()?; - let f = Arc::new(faces(children)); - self.cache = Some(Found { revision: cx.revision, group: g, faces: f.clone() }); - Some((g, f)) + self.cache.as_ref() + } + + /// What hovering `p` highlights ([`IntertwineTool::hover`]). + fn highlight(&mut self, cx: &ToolContext, p: Point) -> Option { + let found = self.found(cx)?; + let face = face_at(&found.faces, p)?; + if face.members.len() >= MENU_MEMBERS + && let Some(a) = nearest_member(&found.areas, &face, p).and_then(|m| found.areas.get(m)).and_then(Option::as_ref) + { + return Some(a.to_bezpath()); + } + Some(face.path.to_bezpath()) } /// The closed path the drag drew. @@ -209,7 +260,7 @@ impl Tool for IntertwineTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = self.faces(cx).and_then(|(_, f)| face_at(&f, p)).map(|f| f.path.to_bezpath()); + self.hover = self.highlight(cx, p); vec![] } PointerKind::Down => { @@ -332,6 +383,43 @@ mod tests { assert_eq!(drawn_order(&kids, &f[0]), [1, 0]); } + #[test] + fn members_drawn_at_higher_tiers_are_drawn_later() { + // Three squares over one another; the bottom one at tier 2, the middle one at tier 1. + let over = || shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 0.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b), square(3, 0.0)]; + let f = faces(&kids); + assert_eq!(f.len(), 1); + assert_eq!(drawn_order(&kids, &f[0]), [2, 1, 0]); + } + + #[test] + fn the_member_nearest_to_the_pointer_is_picked_where_three_overlap() { + // Squares 20 wide from x = 0, 4 and 8: all three overlap from x = 8 to 20. + let wide = + |id: u64, x: f64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default_art())); + let kids = vec![wide(1, 0.0), wide(2, 4.0), wide(3, 8.0)]; + let areas = painted_areas(&kids); + let all = faces_of(&areas); + let face = face_at(&all, Point::new(14.0, 10.0)).unwrap(); + assert_eq!(face.members, [0, 1, 2]); + // By the left edge of the third square, then by the right edge of the first one. + assert_eq!(nearest_member(&areas, &face, Point::new(8.5, 10.0)), Some(2)); + assert_eq!(nearest_member(&areas, &face, Point::new(19.5, 10.0)), Some(0)); + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: kids })).unwrap(); + assert_eq!(menu_target(&d, &[g], Point::new(8.5, 10.0)), Some((g, NodeId(3)))); + assert_eq!(menu_target(&d, &[g], Point::new(19.5, 10.0)), Some((g, NodeId(1)))); + assert_eq!(menu_target(&d, &[g], Point::new(6.0, 10.0)), None, "only two overlap there"); + assert_eq!(menu_target(&d, &[], Point::new(8.5, 10.0)), None, "no Intertwine group selected"); + } + #[test] fn a_lasso_takes_the_areas_whose_inside_it_encloses() { let kids = vec![square(1, 0.0), square(2, 5.0)]; diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 68c1e41327..0790407d2a 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -232,10 +232,12 @@ impl Tool for MeshTool { (Paint::Solid { color, .. }, false) => Some(crate::params::color_json(color)), _ => None, }; + // A click that hits an edge from just outside adds the lines at the edge. + let tol = cx.hit_options().tol; for id in [leaf, top] { match cx.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Mesh(_)) => { - let mut params = json!({"id": id.0, "x": p.x, "y": p.y}); + let mut params = json!({"id": id.0, "x": p.x, "y": p.y, "tolerance": tol}); if let Some(c) = &color { params["color"] = c.clone(); params["keepModel"] = json!(true); @@ -243,10 +245,10 @@ impl Tool for MeshTool { return vec![Action::Exec("object.mesh.addLine".into(), params)]; } Some(NodeKind::Envelope { .. }) if cx.doc.node(id).and_then(grid_of).is_some() => { - return vec![Action::Exec("object.mesh.addLine".into(), json!({"id": id.0, "x": p.x, "y": p.y}))]; + return vec![Action::Exec("object.mesh.addLine".into(), json!({"id": id.0, "x": p.x, "y": p.y, "tolerance": tol}))]; } Some(NodeKind::Path { guide: false, .. }) | Some(NodeKind::Compound { .. }) => { - return vec![Action::Exec("object.mesh.create".into(), json!({"ids": [id.0], "at": [p.x, p.y]}))]; + return vec![Action::Exec("object.mesh.create".into(), json!({"ids": [id.0], "at": [p.x, p.y], "tolerance": tol}))]; } _ => {} } @@ -490,6 +492,9 @@ mod tests { let c = cx(&d, &s, &p); let mut t = create("mesh").unwrap(); let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 160.0)); - assert_eq!(acts, vec![Action::Exec("object.mesh.create".into(), json!({"ids": [a.0], "at": [150.0, 160.0]}))]); + assert_eq!( + acts, + vec![Action::Exec("object.mesh.create".into(), json!({"ids": [a.0], "at": [150.0, 160.0], "tolerance": c.hit_options().tol}))] + ); } } diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index b3904efe41..e0ef779fb5 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -360,7 +360,7 @@ mod tests { // Inside the envelope: a new row and column. assert_eq!( t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 160.0)), - vec![Action::Exec("object.mesh.addLine".into(), json!({"id": e.0, "x": 150.0, "y": 160.0}))] + vec![Action::Exec("object.mesh.addLine".into(), json!({"id": e.0, "x": 150.0, "y": 160.0, "tolerance": c.hit_options().tol}))] ); } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 5586b987df..5620be4d54 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -4,9 +4,10 @@ //! selection and the paint defaults (`appearance.copyFrom`); Alt-click: the selection's attributes //! onto the clicked object (`reverse`); Shift+Alt-click: add the clicked object's appearance to the //! selection's (`append`). Shift-click: sample only the colour under the cursor into the active -//! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK). Clicking -//! an image samples its pixels (averaged over the options' raster sample size; a CMYK image gives -//! its ink amounts). +//! fill/stroke (`paint.sampleColor`; in a CMYK document an RGB color is stored as CMYK): a +//! gradient's color at that point, a pattern's tile art there (after the pattern's transform), or +//! a gradient mesh's interpolated patch color. Clicking an image samples its pixels (averaged over +//! the options' raster sample size; a CMYK image gives its ink amounts). //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor @@ -15,11 +16,14 @@ //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. +use std::collections::HashSet; + use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::hit::{HitKind, hit_test, hit_test_visible}; -use vectorcraft_doc::{Node, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test, hit_test_visible, hit_test_visible_skipping}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Affine, Point, Rect}; use super::paint_owner; use crate::params::color_json; @@ -49,18 +53,142 @@ pub fn paint_color_at(paint: &Paint, bounds: Option, p: } } +/// How many patterns and symbols deep a sample follows art inside art (tile art painted with a +/// pattern, a symbol whose art holds an instance of another). +const MAX_NESTING: usize = 16; + +/// Most tiles of one pattern a sample looks at, front to back, for art that paints the point. +const MAX_TILES: usize = 1_000; + +/// Most work one sample does, in objects looked at: each hit test after the first in a document +/// counts the objects of the document and of its symbols, each pattern tile or symbol instance +/// sampled counts the objects of its art, and every hundred tile positions checked count one. +/// Art inside art multiplies them; a sample that would need more gives no color. +const MAX_WORK: usize = 1_000_000; + +/// One color sample: the document, the hit options, the raster sample size and the work left. +struct Sampler<'a> { + doc: &'a Document, + opts: HitOptions, + raster_sample: u32, + /// The objects in the art of the document's symbols, which a hit test may measure. + symbol_nodes: usize, + work: usize, + /// The work ran out: the sample gives no color. + exhausted: bool, +} + +impl Sampler<'_> { + /// Count `n` units of work, or `None` when that is more than is left. + fn spend(&mut self, n: usize) -> Option<()> { + match self.work.checked_sub(n) { + Some(left) => { + self.work = left; + Some(()) + } + None => { + self.work = 0; + self.exhausted = true; + None + } + } + } +} + +/// The Eyedropper's hit options: a click inside a fill or among characters samples it too, +/// whatever Object and Type Object Selection by Path Only say. +fn sample_options(cx: &ToolContext) -> HitOptions { + HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() } +} + /// The visible object under `p`, using the Eyedropper's source selection rules. pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_doc::NodeId, HitKind)> { - let opts = vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() }; - let h = hit_test_visible(cx.doc, p, opts)?; + let h = hit_test_visible(cx.doc, p, sample_options(cx))?; Some((paint_owner(cx.doc, h.leaf), h.kind)) } -/// The visible color under `p`, including image pixels and intermediate gradient colors. +/// The visible color under `p`, including image pixels, pattern tiles, mesh colors and +/// intermediate gradient colors. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { - let (id, kind) = sample_source(cx, p)?; - let n = cx.doc.node(id)?; - if matches!(n.kind, NodeKind::Image(_)) { image_color_at(cx, n, p) } else { paint_sample(n, kind == HitKind::Stroke, p) } + let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); + vectorcraft_doc::depth::with_deep_stack(|| { + let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum(); + let mut s = Sampler { doc, opts, raster_sample, symbol_nodes, work: MAX_WORK, exhausted: false }; + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let c = color_under(&mut s, doc, &mut levels, p, opts); + c.filter(|_| !s.exhausted) + }) +} + +/// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke +/// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; +/// an object that gives none at all is passed over for the ones below it. `levels` holds the +/// scratch documents for art inside art, one for each level deeper. +fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], p: Point, opts: HitOptions) -> Option { + let mut passed: HashSet = HashSet::new(); + let mut size = None; + loop { + // The first hit test is the one a click makes anyway; each one after it may visit every + // object again. + let cost = + if passed.is_empty() { 1 } else { *size.get_or_insert_with(|| s.symbol_nodes + doc.layers.iter().map(|l| l.count()).sum::()) }; + s.spend(cost)?; + let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; + let id = paint_owner(doc, h.leaf); + let n = doc.node(id)?; + let on_stroke = h.kind == HitKind::Stroke; + if let Some(c) = node_color_at(s, levels, n, on_stroke, p) { + return Some(c); + } + if on_stroke + && fill_covers(n, p) + && let Some(c) = node_color_at(s, levels, n, false, p) + { + return Some(c); + } + if !passed.insert(id) { + return None; + } + } +} + +/// Whether the fill of path or compound path `n` covers `p`. +fn fill_covers(n: &Node, p: Point) -> bool { + match &n.kind { + NodeKind::Path { path, rule, .. } => fill_contains(&path.to_bezpath(), *rule, p), + NodeKind::Compound { rule, .. } => n.stroke_path().is_some_and(|bp| fill_contains(&bp, *rule, p)), + _ => false, + } +} + +/// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol +/// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no +/// fill) there. Images, symbols and patterns are looked up in the sampled document. +fn node_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, on_stroke: bool, p: Point) -> Option { + match &n.kind { + NodeKind::Image(_) => image_color_at(s, n, p), + NodeKind::Mesh(m) => { + let (r, c, u, v) = m.locate(p)?; + Some(m.color_at(r, c, u, v).0) + } + // The instance's fill only stains its art: where the art paints nothing, nothing shows. + NodeKind::SymbolInstance { symbol, xf } => symbol_color_at(s, levels, n, symbol, *xf, p), + _ => paint_sample(s, levels, n, on_stroke, p), + } +} + +/// The color the art of symbol `name` shows at `p` as instance `inst` draws it: stained by the +/// instance's fill and placed in the document by `xf`, its strokes and patterns unscaled. +fn symbol_color_at(s: &mut Sampler, levels: &mut [Option], inst: &Node, name: &str, xf: Affine, p: Point) -> Option { + if xf.determinant().abs() < 1e-12 { + return None; + } + let doc = s.doc; + let sym = doc.symbols.iter().find(|s| s.name == name)?; + s.spend(sym.art.count())?; + let mut art = vectorcraft_brush::instance_art(&sym.art, inst); + art.transform(xf, false); + art_color_at(s, levels, [art], p) } /// Whether the source has fill or stroke paint for an attribute sample. @@ -69,30 +197,111 @@ pub(crate) fn has_sampleable_paint(cx: &ToolContext, id: vectorcraft_doc::NodeId } /// The colour of `n`'s fill (or its stroke, when the stroke was hit or there is no fill) at `p`, -/// sampled in the paint's own space (text space for type runs) and box. -fn paint_sample(n: &Node, on_stroke: bool, p: Point) -> Option { +/// sampled in the paint's own space (text space for type runs) and box. A pattern gives the color +/// of its tile art at `p` ([`pattern_color_at`]). +fn paint_sample(s: &mut Sampler, levels: &mut [Option], n: &Node, on_stroke: bool, p: Point) -> Option { let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none()); let (paint, to_doc, bounds) = n.proxy_paint(on_stroke || fill_none, None)?; + if let Paint::Pattern { pattern, xf } = paint { + return pattern_color_at(s, levels, pattern, to_doc * *xf, p); + } let p = if to_doc.determinant().abs() > 1e-12 { to_doc.inverse() * p } else { p }; paint_color_at(paint, Some(bounds), p) } -/// The color of image `n`'s pixels at `p`, averaged over the raster sample size: a CMYK image's -/// ink amounts as they are, other images' sRGB pixels in the working RGB space (the color that -/// shows as that pixel). -fn image_color_at(cx: &ToolContext, n: &Node, p: Point) -> Option { +/// The color pattern `name`, placed in the document by `xf`, shows at `p`: the color of the +/// front-most tile art there. A point the tiles leave empty has no color. +fn pattern_color_at(s: &mut Sampler, levels: &mut [Option], name: &str, xf: Affine, p: Point) -> Option { + if xf.determinant().abs() < 1e-12 { + return None; + } + let doc = s.doc; + let def = doc.patterns.iter().find(|d| d.name == name)?; + // Sampled in pattern space, one tile at a time from the front, among the tiles whose art reaches + // the point (or meets it at an edge). The art moves by whole tiles, and the patterns it is + // painted with move with it. + let q = xf.inverse() * p; + let near = Rect::from_points(q, q).inflate(1e-6, 1e-6); + let (mut art_nodes, mut instances) = (0, false); + for a in &def.art { + a.walk(&mut |n| { + art_nodes += 1; + instances |= matches!(n.kind, NodeKind::SymbolInstance { .. }); + }); + } + // Symbol instances in the art are measured by their symbols' art. + s.spend(1 + art_nodes + if instances { s.symbol_nodes } else { 0 })?; + let symbols = doc.symbol_boxes(); + let bounds: Vec> = def.art.iter().map(|a| a.visual_bounds_with(&symbols)).collect(); + let reaches = |m: Affine| bounds.iter().any(|b| b.is_none_or(|b| m.transform_rect_bbox(b).inflate(1e-6, 1e-6).contains(q))); + let scaling = vectorcraft_doc::Scaling { patterns: true, ..Default::default() }; + let offsets = def.offsets_covering(near); + // Each tile position is checked against each piece of art: a hundred checks count as one unit. + s.spend(offsets.len().saturating_mul(bounds.len().max(1)) / 100)?; + for m in offsets.into_iter().rev().map(|o| def.instance_xf(o)).filter(|m| reaches(*m)).take(MAX_TILES) { + s.spend(1 + art_nodes)?; + let art = def.art.iter().map(|a| { + let mut n = (**a).clone(); + vectorcraft_doc::pattern::place_art(&mut n, m, scaling); + n + }); + if let Some(c) = art_color_at(s, levels, art, q) { + return Some(c); + } + } + None +} + +/// The color the front-most of `art` (in paint order, in the space of `p`) shows at `p`, sampled +/// as [`node_color_at`] samples an object, with no tolerance around outlines and strokes: only +/// what it paints at `p` counts. The art is hit in the first of `levels`, a scratch document with +/// the sampled document's symbols, made on first use and emptied for each new piece of art; art +/// inside it uses the levels after it. With no level left, the art gives no color. +fn art_color_at(s: &mut Sampler, levels: &mut [Option], art: impl IntoIterator, p: Point) -> Option { + let (slot, deeper) = levels.split_first_mut()?; + let doc = s.doc; + let scratch = slot.get_or_insert_with(|| { + let mut d = Document::new(1.0, 1.0); + d.symbols = doc.symbols.clone(); + d + }); + let layer = scratch.layers.first()?; + let (layer, placed) = (layer.id, layer.children().map(|c| c.iter().map(|n| n.id).collect::>()).unwrap_or_default()); + for id in placed { + scratch.remove(id).ok()?; + } + for mut n in art { + renumber(scratch, &mut n); + scratch.insert(Some(layer), usize::MAX, n).ok()?; + } + let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..s.opts }; + color_under(s, scratch, deeper, p, opts) +} + +/// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). +fn renumber(doc: &mut Document, n: &mut Node) { + n.id = doc.alloc_id(); + for c in n.children_mut().into_iter().flatten() { + renumber(doc, std::sync::Arc::make_mut(c)); + } +} + +/// The color of image `n`'s pixels at `p`, averaged over the raster sample size: a CMYK image's ink +/// amounts as they are, other images' sRGB pixels in the working RGB space (the color that shows +/// as that pixel). +fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option { let NodeKind::Image(im) = &n.kind else { return None }; if im.xf.determinant().abs() < 1e-12 { return None; } let px = im.xf.inverse() * p; - let blob = cx.doc.images.get(&im.key)?; + let blob = s.doc.images.get(&im.key)?; let object = (im.width, im.height); - if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, cx.raster_sample) { + if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, s.raster_sample) { let [c, m, y, k] = inks.map(|v| f32::from(v) / 255.0); return Some(Color::cmyk(c, m, y, k)); } - let [r, g, b, _] = blob.sample_object(px.x, px.y, object, cx.raster_sample)?; + let [r, g, b, _] = blob.sample_object(px.x, px.y, object, s.raster_sample)?; let [r, g, b] = vectorcraft_color::cms::active().srgb_to_rgb([r, g, b].map(|v| f32::from(v) / 255.0)); Some(Color::rgb(r, g, b)) } @@ -106,9 +315,7 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } - // A click inside a fill or among characters samples it too, whatever Object and Type - // Object Selection by Path Only say. - let opts = vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..cx.hit_options() }; + let opts = sample_options(cx); if self.brush_key_color { let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let back = self.stop.clone().unwrap_or_else(|| "selection".to_string()); @@ -124,7 +331,7 @@ impl Tool for EyedropperTool { } else { sample_source(cx, ev.pos) }; - let Some((src, kind)) = source else { return vec![] }; + let Some((src, _)) = source else { return vec![] }; let Some(n) = cx.doc.node(src) else { return vec![] }; if ev.mods.alt && stop.is_none() { let how = if ev.mods.shift { "append" } else { "reverse" }; @@ -134,8 +341,7 @@ impl Tool for EyedropperTool { if !(ev.mods.shift || stop.is_some() || image) { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; } - let sampled = if image { image_color_at(cx, n, ev.pos) } else { paint_sample(n, kind == HitKind::Stroke, ev.pos) }; - let Some(c) = sampled else { return vec![] }; + let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let color = color_json(&c); let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; @@ -389,6 +595,272 @@ mod tests { ); } + /// An unstroked rectangle filled with `fill`, with id 0 (as pattern and symbol art is). + fn filled_rect(r: vectorcraft_geom::Rect, fill: Paint) -> std::sync::Arc { + let mut a = vectorcraft_doc::Appearance::default(); + a.set_fill(fill); + std::sync::Arc::new(Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::shapes::rectangle(r), a)) + } + + /// [`doc_with_rect`] plus the pattern "Halves": a 20 × 10 tile, red on its left half and blue + /// on its right half. + fn doc_with_halves() -> (vectorcraft_doc::Document, vectorcraft_doc::NodeId) { + use vectorcraft_geom::Rect; + let (mut d, id) = doc_with_rect(); + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let mut def = vectorcraft_doc::PatternDef::new( + "Halves", + vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red), filled_rect(Rect::new(10.0, 0.0, 20.0, 10.0), blue)], + ); + def.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(def); + (d, id) + } + + /// Shift-click on a pattern fill samples the color of the tile art under the cursor, where the + /// pattern's own transform puts it, however small the tiles are. + #[test] + fn shift_click_samples_the_pattern_tile_under_the_cursor() { + use vectorcraft_geom::Affine; + let (mut d, id) = doc_with_halves(); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Pattern { pattern: "Halves".into(), xf: Affine::translate((5.0, 0.0)) }); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64| { + EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 155.0).with_mods(shift)) + }; + // Pattern space x 128 (8 into a tile), then x 137 (17 into a tile). + assert_eq!(sampled_hex(&at(&d, 133.0)), "#ff0000"); + assert_eq!(sampled_hex(&at(&d, 142.0)), "#0000ff"); + assert_eq!(crate::xform::eyedropper::sample_color_at(&cx(&d, &s, &p), Point::new(142.0, 155.0)).map(|c| c.to_hex()), Some("#0000ff".into())); + // Art 300 pt wide on a 1 pt tile: about 90,000 tiles reach every point. + let mut wide = vectorcraft_doc::PatternDef::new( + "Wide", + vec![filled_rect(vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)))], + ); + wide.tile = vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0); + let mut wide_doc = d.clone(); + wide_doc.patterns.push(wide); + wide_doc.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Wide")); + assert_eq!(sampled_hex(&at(&wide_doc, 142.0)), "#00ff00"); + // Pattern space x 140, on the edge between two tiles. + let edge = sampled_hex(&at(&d, 145.0)); + assert!(edge == "#ff0000" || edge == "#0000ff", "{edge}"); + // Tiles 0.2 × 0.1 pt, 0.05 pt down: pattern space y 15495, x 15005 (5 into a tile), then + // x 15015 (15 into a tile). + let tiny = Affine::translate((0.0, 0.05)) * Affine::scale(0.01); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Pattern { pattern: "Halves".into(), xf: tiny }); + assert_eq!(sampled_hex(&at(&d, 150.05)), "#ff0000"); + assert_eq!(sampled_hex(&at(&d, 150.15)), "#0000ff"); + } + + /// Tile art painted with another pattern is sampled where that tile draws it: the inner + /// pattern moves with each tile. A symbol instance is sampled from its symbol's art. + #[test] + fn shift_click_samples_patterns_and_symbols_inside_art() { + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_halves(); + // A 30 pt tile filled with "Halves": every other tile starts halfway through a "Halves" tile. + let mut outer = vectorcraft_doc::PatternDef::new( + "Outer", + vec![filled_rect(Rect::new(0.0, 0.0, 30.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves"))], + ); + outer.tile = Rect::new(0.0, 0.0, 30.0, 10.0); + d.patterns.push(outer); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Outer")); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + // The tile at x 150 draws "Halves" from x 150: x 165 is 15 into it. + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 165.0, 155.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#0000ff"); + // A symbol of a green square, placed at (300, 300) and doubled. + d.symbols.push(vectorcraft_doc::Symbol { + name: "Green".into(), + art: filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0))), + }); + let l = d.layers[0].id; + let inst = d.alloc_id(); + let kind = NodeKind::SymbolInstance { symbol: "Green".into(), xf: Affine::translate((300.0, 300.0)) * Affine::scale(2.0) }; + d.insert(Some(l), usize::MAX, Node::new(inst, kind)).unwrap(); + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 310.0, 310.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#00ff00"); + } + + /// A symbol instance is sampled as it draws: its art stained by the instance's fill, and a + /// pattern in its art left where the document puts it when the instance moves. + #[test] + fn symbol_samples_follow_the_instances_stain_and_placement() { + use vectorcraft_geom::{Affine, Rect}; + let (mut d, _) = doc_with_halves(); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Red".into(), art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), red) }); + d.symbols.push(vectorcraft_doc::Symbol { + name: "Tiled".into(), + art: filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), vectorcraft_doc::pattern::pattern_paint("Halves")), + }); + let l = d.layers[0].id; + let place = |d: &mut vectorcraft_doc::Document, name: &str, at: (f64, f64), stain: Option| { + let id = d.alloc_id(); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate(at) }); + if let Some(c) = stain { + n.appearance.set_fill(Paint::solid(c)); + } + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + place(&mut d, "Red", (300.0, 300.0), Some(Color::rgb(0.0, 0.0, 1.0))); + place(&mut d, "Tiled", (310.0, 400.0), None); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |x: f64, y: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift))) + }; + assert_eq!(at(305.0, 305.0), "#0000ff", "stained"); + // Document x 312 is 12 into a "Halves" tile, though only 2 into the instance's art. + assert_eq!(at(312.0, 405.0), "#0000ff", "pattern in place"); + } + + /// Between the shapes of a stained instance's art, the eyedropper samples what lies below, not + /// the stain; and a pattern tile is sampled wherever its symbol art reaches. + #[test] + fn symbol_art_decides_where_an_instance_paints() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let pair = + Node::group(NodeId(0), vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), red()), filled_rect(Rect::new(20.0, 0.0, 30.0, 10.0), red())]); + d.symbols.push(vectorcraft_doc::Symbol { name: "Pair".into(), art: Arc::new(pair) }); + let (l, inst) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Pair".into(), xf: Affine::translate((100.0, 140.0)) }); + n.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + d.insert(Some(l), usize::MAX, n).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64, y: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift))) + }; + assert_eq!((at(&d, 105.0, 145.0), at(&d, 115.0, 145.0)), ("#0000ff".to_string(), "#ffffff".to_string())); + // A 200 pt tile holding an instance of a 180 pt green bar, which reaches far past the + // square an instance is measured by without its symbol. + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(vectorcraft_doc::Symbol { name: "Bar".into(), art: filled_rect(Rect::new(0.0, 0.0, 180.0, 10.0), green) }); + let bar = Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })); + let mut bars = vectorcraft_doc::PatternDef::new("Bars", vec![bar]); + bars.tile = Rect::new(0.0, 0.0, 200.0, 10.0); + d.patterns.push(bars); + d.node_mut(id).unwrap().appearance.set_fill(vectorcraft_doc::pattern::pattern_paint("Bars")); + assert_eq!(at(&d, 150.0, 155.0), "#00ff00"); + } + + /// Patterns whose tile art is painted with the next one, on tiles far smaller than their art, + /// symbols whose art holds four instances of the next, and symbols nested far deeper than a + /// sample follows: each sample stops within its work limit and gives no color, instead of + /// trying every tile or instance at every level or running out of stack. + #[test] + fn nested_patterns_and_symbols_sample_within_the_work_limit() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_doc::{NodeId, Symbol}; + use vectorcraft_geom::{Affine, Rect}; + let (mut d, id) = doc_with_rect(); + // "Nest0" to "Nest7": 300 pt art on 1 pt tiles, each painted with the next. "Nest8" doesn't + // exist, so no tile gives a color and every one is tried. + for i in 0..8 { + let mut def = vectorcraft_doc::PatternDef::new( + &format!("Nest{i}"), + vec![filled_rect(Rect::new(0.0, 0.0, 300.0, 300.0), pattern_paint(&format!("Nest{}", i + 1)))], + ); + def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + d.patterns.push(def); + } + d.node_mut(id).unwrap().appearance.set_fill(pattern_paint("Nest0")); + // "Fan0" to "Fan11": four instances of the next symbol; "Fan12" a square filled with "Nest8". + let instance = |name: String| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY })); + for i in 0..12 { + let art = Node::group(NodeId(0), (0..4).map(|_| instance(format!("Fan{}", i + 1))).collect()); + d.symbols.push(Symbol { name: format!("Fan{i}"), art: Arc::new(art) }); + } + d.symbols.push(Symbol { name: "Fan12".into(), art: filled_rect(Rect::new(300.0, 300.0, 400.0, 400.0), pattern_paint("Nest8")) }); + // "Deep0" to "Deep99": one instance of the next; "Deep100" a green square. + for i in 0..100 { + d.symbols.push(Symbol { name: format!("Deep{i}"), art: instance(format!("Deep{}", i + 1)) }); + } + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + d.symbols.push(Symbol { name: "Deep100".into(), art: filled_rect(Rect::new(300.0, 0.0, 400.0, 100.0), green) }); + let l = d.layers[0].id; + for name in ["Fan0", "Deep0"] { + let inst = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let (s, p) = (Selection::default(), paint()); + let start = std::time::Instant::now(); + for at in [Point::new(150.0, 150.0), Point::new(350.0, 350.0), Point::new(350.0, 50.0)] { + assert_eq!(sample_color_at(&cx(&d, &s, &p), at), None, "{at:?}"); + } + assert!(start.elapsed() < std::time::Duration::from_secs(60), "{:?}", start.elapsed()); + } + + /// A gap between a pattern's tile art shows what lies below it, in the document and in the tile + /// art of another pattern. + #[test] + fn a_gap_in_a_pattern_samples_what_lies_below() { + use vectorcraft_doc::pattern::pattern_paint; + use vectorcraft_geom::Rect; + // The white rectangle (100, 100)–(200, 200), under one filled with red 10 pt squares 20 pt apart. + let (mut d, _) = doc_with_rect(); + let mut gappy = + vectorcraft_doc::PatternDef::new("Gappy", vec![filled_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))]); + gappy.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(gappy); + let (l, top) = (d.layers[0].id, d.alloc_id()); + let mut over = (*filled_rect(Rect::new(100.0, 100.0, 200.0, 200.0), pattern_paint("Gappy"))).clone(); + over.id = top; + d.insert(Some(l), usize::MAX, over).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let at = |d: &vectorcraft_doc::Document, x: f64| { + sampled_hex(&EyedropperTool::default().pointer(&cx(d, &s, &p), &PointerEvent::new(PointerKind::Down, x, 155.0).with_mods(shift))) + }; + // x 125 is 5 into a tile, on a red square; x 133 is 13 into one, between them. + assert_eq!((at(&d, 125.0), at(&d, 133.0)), ("#ff0000".to_string(), "#ffffff".to_string())); + // Tile art: a green rectangle behind one filled with "Gappy". + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let mut lined = vectorcraft_doc::PatternDef::new( + "Lined", + vec![filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), green), filled_rect(Rect::new(0.0, 0.0, 20.0, 10.0), pattern_paint("Gappy"))], + ); + lined.tile = Rect::new(0.0, 0.0, 20.0, 10.0); + d.patterns.push(lined); + d.node_mut(top).unwrap().appearance.set_fill(pattern_paint("Lined")); + assert_eq!((at(&d, 125.0), at(&d, 133.0)), ("#ff0000".to_string(), "#00ff00".to_string())); + // A blue fill under a 20 pt stroke of "Gappy", 5 pt left: x 107 is 12 into a tile, in a gap + // of the stroke over the fill. + let shape = &mut d.node_mut(top).unwrap().appearance; + shape.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + shape.set_stroke(Paint::Pattern { pattern: "Gappy".into(), xf: vectorcraft_geom::Affine::translate((-5.0, 0.0)) }); + shape.stroke_mut().unwrap().width = 20.0; + assert_eq!((at(&d, 103.0), at(&d, 107.0)), ("#ff0000".to_string(), "#0000ff".to_string())); + } + + /// Shift-click on a gradient mesh samples the patch color interpolated at the cursor. + #[test] + fn shift_click_samples_the_mesh_color_under_the_cursor() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + // Black on the left edge, white on the right edge. + let mesh = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|u, _| { + if u < 0.5 { Color::rgb(0.0, 0.0, 0.0) } else { Color::rgb(1.0, 1.0, 1.0) } + }); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 125.0, 150.0).with_mods(shift)); + assert_eq!(sampled_hex(&a), "#404040"); + } + #[test] fn gradient_sampled_along_vector() { let g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()); diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 8db01d4223..38311b773d 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -4,7 +4,9 @@ use super::{Ui, VectorcraftApp, Xf, json, widgets}; /// Right-click: the object under the pointer is selected first unless it already is, then the /// context menu lists what applies to the selection ([`crate::menus::context_items`]). The locked /// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in -/// `ui.context_locked` while the menu is open, for its Unlock submenu. +/// `ui.context_locked` while the menu is open, for its Unlock submenu. With the Intertwine tool, a +/// right-click where three or more objects of the group overlap keeps the selection and puts what +/// it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: &Xf) { if resp.secondary_clicked() && let Some(p) = resp.interact_pointer_pos() @@ -12,7 +14,13 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: let p = xf.to_doc(p); let locked = hit_with(app, p, xf.zoom, |doc, p, opt| Some(vectorcraft_doc::hit::locked_objects_at(doc, p, opt))); app.ui.context_locked = app.session.active().map(|st| st.uid).zip(locked); - if let Some(st) = app.session.active() + app.ui.context_intertwine = app + .session + .active() + .filter(|_| app.session.tool_id() == "intertwine") + .and_then(|st| vectorcraft_tools::intertwine::menu_target(&st.doc, &st.selection.objects, p).map(|(g, m)| (st.uid, g, p, m))); + if app.ui.context_intertwine.is_none() + && let Some(st) = app.session.active() && let Some(top) = selection_hit_at(app, p, xf.zoom).map(|h| h.top_object(st.isolation)) && !st.selection.contains(top) { @@ -23,6 +31,7 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: let mut clicked = None; if resp.context_menu(|ui| crate::menus::context_menu_body(app, ui, &mut clicked)).is_none() { app.ui.context_locked = None; + app.ui.context_intertwine = None; } if let Some((id, p)) = clicked { crate::menus::invoke(app, &id, p); diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 1a978a4c7e..5b8b3435c3 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -185,8 +185,9 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c // Preferences ▸ Units ▸ General does ([`crate::menus::ruler_menu_body`]). let mut unit_clicked = None; for (r, vertical, id) in [(top, false, "ruler-top"), (left, true, "ruler-left")] { - // Click-and-drag so the same widget drags out guides (left) and opens the unit menu (right). - let resp = ui.interact(r, egui::Id::unique(id), Sense::click_and_drag()); + // Clicks and drags so the same widget drags out guides (left) and opens the unit menu + // (right). Not focusable (`click_and_drag` is): no key acts on a ruler, so Tab skips it. + let resp = ui.interact(r, egui::Id::unique(id), Sense::CLICK | Sense::DRAG); resp.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); let kind = if resp.drag_stopped() { PointerKind::Up @@ -212,7 +213,8 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c app.status(e.to_string()); } } - let corner = ui.interact(corner, egui::Id::unique("ruler-corner"), Sense::click_and_drag()); + // Not focusable either: no key acts on the box. + let corner = ui.interact(corner, egui::Id::unique("ruler-corner"), Sense::CLICK | Sense::DRAG); corner.context_menu(|ui| crate::menus::ruler_menu_body(app, ui, &mut unit_clicked)); if let Some((id, p)) = unit_clicked { crate::menus::invoke(app, &id, p); diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 61c9719878..73a6334866 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -33,6 +33,7 @@ fn picked_artboards_bounds(app: &VectorcraftApp) -> Option { /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions. /// With the Artboard tool it sits under the selected artboards and offers Resize (Artboard /// Options), Duplicate, Rearrange All (with two or more artboards) and Export (Export for Screens). +/// A basic shape selected with the Selection tool shows a Shape Properties button in place of Lock. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { @@ -67,6 +68,17 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { && first.as_ref().is_some_and(|f| { f.name.as_deref() == Some("Image Trace") && f.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) }); + // A basic shape (a live rectangle, rounded rectangle, ellipse or polygon) selected whole with the + // Selection tool: its properties take the place of Lock, as in the reference app + // (). + use vectorcraft_doc::LiveShape; + let shape = first.clone().filter(|f| { + n == 1 + && st.selection.anchors.is_empty() + && app.session.tool_id() == "selection" + && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } + if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) + }); let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) let none = || json!({}); if on_artboards { @@ -228,7 +240,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((*cmd, params.clone())); } } - // The selected objects' Fill, Stroke, Recolor Artwork and Lock, left out with the Artboard tool. + // The selected objects' Fill, Stroke, Recolor Artwork and Lock (a basic shape's + // properties instead), left out with the Artboard tool. if !on_artboards { let (r, resp) = ui.allocate_exact_size(vec2(26.0, 30.0), Sense::click()); let chip = egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)); @@ -251,10 +264,22 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 30.0).clicked() { run = Some(("ui.recolorDialog", json!({}))); } - // The Lock button is off in isolation mode, as Object › Lock › Selection is. - let lockable = crate::menus::enabled(app, "object.lock"); - if widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked() { - run = Some(("object.lock", json!({}))); + if let Some(shape) = &shape + && let NodeKind::Path { live: Some(live), .. } = &shape.kind + { + // The shape's properties in a popover that stays open while its fields and + // its Corner dropdown are used. + let props = widgets::icon_button(ui, "shapes", tl!("Shape Properties"), false, 30.0); + widgets::popover(&props, props.clicked(), |ui| { + ui.set_min_width(250.0); + crate::panels::transform::live_shape_rows(app, ui, shape, live, "task-bar-shape", true); + }); + } else { + // The Lock button is off in isolation mode, as Object › Lock › Selection is. + let lockable = crate::menus::enabled(app, "object.lock"); + if widgets::icon_button_enabled(ui, "lock", tl!("Lock (⌘2)"), false, lockable, 30.0).clicked() { + run = Some(("object.lock", json!({}))); + } } } let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, 30.0); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ed67da7129..f7361da0ca 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6839,7 +6839,8 @@ fn the_task_bar_shows_a_stroke_chip_beside_fill() { let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); out.textures_delta.clear(); let bar = task_bar_rect(&ctx).expect("the task bar shows"); - // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), Recolor, + // then Stroke and Fill. let stroke_x = bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; let fill_x = stroke_x - 26.0 - 6.0; let blue = Color32::from_rgb(0x22, 0x44, 0xcc); @@ -6896,7 +6897,8 @@ fn the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere() { out.textures_delta.clear(); out.shapes }; - // Right to left: the frame's margin, More Options, Lock, Recolor, then Stroke and Fill. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), Recolor, + // then Stroke and Fill. let stroke_x = |bar: egui::Rect| bar.right() - 8.0 - 3.0 * (30.0 + 6.0) - 13.0; let chip_with = |shapes: &[egui::epaint::ClippedShape], bar: egui::Rect, x: f32, color: Color32| { shapes.iter().any(|c| match &c.shape { @@ -6948,7 +6950,7 @@ fn the_task_bar_recolors_coloured_art() { frame(app, &ctx, vec![]); frame(app, &ctx, vec![]); let bar = task_bar_rect(&ctx).expect("the task bar shows"); - // Right to left: the frame's margin, More Options, Lock, then Recolor. + // Right to left: the frame's margin, More Options, Shape Properties (Lock's place), then Recolor. let at = pos2(bar.right() - 8.0 - 30.0 - 6.0 - 30.0 - 6.0 - 15.0, bar.center().y); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); @@ -6969,15 +6971,18 @@ fn the_task_bar_recolors_coloured_art() { assert!(app.ui.dialog.is_none(), "no Recolor button without colours"); } -/// The Contextual Task Bar's Lock button is off in isolation mode, as Object › Lock › Selection -/// is: a click locks nothing and shows no error. Outside isolation mode it locks the selection. +/// The Contextual Task Bar's Lock button locks the selected member in isolation mode and the +/// selected group outside isolation mode. #[test] -fn the_task_bar_lock_button_is_off_in_isolation_mode() { +fn the_task_bar_lock_button_locks_selected_art_in_isolation_mode() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let a = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); - let b = app.session.execute("shape.rectangle", &json!({"x": 210, "y": 130, "width": 40, "height": 40})).unwrap()["id"].clone(); - app.session.execute("select.set", &json!({"ids": [a.clone(), b]})).unwrap(); + // Plain paths: a basic shape shows its properties in Lock's place. + let square = + |x: f64| json!({"anchors": [{"x": x, "y": 130}, {"x": x + 40.0, "y": 130}, {"x": x + 40.0, "y": 170}, {"x": x, "y": 170}], "closed": true}); + let a = app.session.execute("path.create", &square(150.0)).unwrap()["id"].clone(); + let b = app.session.execute("path.create", &square(210.0)).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [a.clone(), b.clone()]})).unwrap(); let g = app.session.execute("object.group", &json!({})).unwrap()["id"].clone(); app.select_tool("selection"); let ctx = egui::Context::default(); @@ -6998,7 +7003,8 @@ fn the_task_bar_lock_button_is_off_in_isolation_mode() { app.session.execute("object.isolate", &json!({"id": g.clone()})).unwrap(); app.session.execute("select.set", &json!({"ids": [a.clone()]})).unwrap(); click_lock(&mut app); - assert!(!locked(&app, &a), "nothing is locked in isolation mode"); + assert!(locked(&app, &a), "the selected member is locked in isolation mode"); + assert!(!locked(&app, &b), "the other member stays unlocked"); assert_eq!(app.ui.status, "", "no error"); app.session.execute("object.exitIsolation", &json!({})).unwrap(); app.session.execute("select.set", &json!({"ids": [g.clone()]})).unwrap(); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 06d2964a7c..99ca027cb2 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -178,7 +178,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { crumbs.push(Crumb { id: None, is_layer: false, name: pn.clone() }); } let bar = egui::Rect::from_min_size(area.min, vec2(area.width(), 24.0)); - ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::click_and_drag()); + // Keeps the pointer off the canvas; not focusable (`click_and_drag` is), so Tab skips it. + ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG); ui.painter().rect_filled(bar, 0.0, t.panel); let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0)); let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click()); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 798777d7ea..e021354af6 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -973,6 +973,35 @@ fn isolation_bar_navigation_and_back_button_steps_up() { assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); } +/// Tab goes to the isolation bar's back button and breadcrumbs and does not stop on the bar +/// behind them, which only keeps the pointer off the canvas. +#[test] +fn tab_skips_the_isolation_bars_background() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 50, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("object.isolate", json!({"id": a})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + let mut frame = |events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| { + super::isolation_bar(&mut app, ui, screen); + }); + out.textures_delta.clear(); + }; + frame(vec![]); + let bar = egui::Rect::from_min_size(screen.min, egui::vec2(screen.width(), 24.0)); + let bar = ctx.viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.rect == bar).map(|w| w.id)); + let bar = bar.expect("the isolation bar"); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 10, frame); + assert!(!stops.is_empty(), "Tab reaches the back button and the breadcrumbs"); + assert!(!stops.contains(&bar), "{stops:?}"); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 83e7850f4e..a4eac70418 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -12,7 +12,9 @@ pub mod action_set_options; pub mod artboard_options; pub mod blend_options; mod brush_art_options; +pub mod brush_delete; pub mod brush_options; +pub mod char_style_options; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -106,6 +108,7 @@ pub mod spot_colors; pub(crate) mod svg_options; pub mod swatch_conflict; pub mod swatch_options; +pub mod symbol_delete; pub mod symbol_options; pub mod symbolism_options; mod text_export; @@ -175,6 +178,8 @@ pub(crate) struct DialogSpec { pub confirm: fn(&mut VectorcraftApp, &Dialog) -> DialogResult, /// The OK button's label. None: no OK button, Enter does nothing and Cancel reads "Close". pub ok: Option<&'static str>, + /// The Cancel button's label when it is not "Cancel" ("No"). Only with an `ok`. + pub cancel: Option<&'static str>, /// An extra button left of Cancel that sets `discard: true` and confirms ("Don't Save"). pub discard: Option<&'static str>, /// A button left of Cancel, as (label, field), that sets `field: true` and confirms, as OK @@ -217,6 +222,7 @@ impl DialogSpec { Ok(Value::Null) }, ok: Some("OK"), + cancel: None, discard: None, alternate: None, reset: None, @@ -289,6 +295,7 @@ registry! { FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)), SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC, Confirm: [confirm::KIND] => confirm::SPEC, + BrushDelete: [brush_delete::KIND] => brush_delete::SPEC, Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC, Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, @@ -300,6 +307,7 @@ registry! { GradientStop: ["gradientStop"] => gradient_stop::SPEC, ColorPicker: [color_picker::KIND] => color_picker::SPEC, GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC, + CharStyleOptions: [char_style_options::KIND] => char_style_options::SPEC, NewTextStyle: [new_text_style::KIND] => new_text_style::SPEC, EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC, ColorGuideOptions: [color_guide_options::KIND] => color_guide_options::SPEC, @@ -371,6 +379,8 @@ registry! { ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, + DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, + DeleteUsedSymbol: [symbol_delete::USED] => symbol_delete::USED_SPEC, SymbolismOptions: [symbolism_options::KIND] => symbolism_options::SPEC, PerspectiveGridPresets: [perspective_presets::KIND] => perspective_presets::SPEC, PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC, @@ -397,6 +407,7 @@ pub fn button_labels() -> Vec<&'static str> { let mut v = vec!["Cancel", "Close"]; for spec in std::iter::once(&DialogSpec::FORM).chain(DialogKind::ALL.iter().map(|k| k.spec())) { v.extend(spec.ok); + v.extend(spec.cancel); v.extend(spec.discard); v.extend(spec.alternate.map(|(label, _)| label)); v.extend(spec.reset.map(|_| "Reset")); @@ -638,7 +649,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let label = if resets { "Reset" } else if spec.ok.is_some() { - "Cancel" + spec.cancel.unwrap_or("Cancel") } else { "Close" }; diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 01c27b98aa..3464fad755 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -21,26 +21,28 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result Value { + json!({ + "set": set, + "action": action, + "actionName": name, + "source": "folder", + "datasetFileNaming": "fileNumber", + "folder": "", + "includeSubdirs": false, + "destination": "folder", + "destinationFolder": "", + "overrideOpen": true, + "overrideSave": true, + "overrideExport": true, + "stopOnError": true, + }) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(d.str("actionName")).color(t.text_strong)); @@ -58,6 +60,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "includeSubdirs", "Include All Subdirectories"); } else { ui.label(egui::RichText::new(tl!("Uses every data set of the open document.")).size(11.5).color(t.text_dim)); + form::choice( + ui, + d, + "datasetFileNaming", + "File Name:", + (LABEL, 200.0), + &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], + ); } ui.add_space(8.0); @@ -95,23 +105,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if source == "datasets" && app.session.active().is_none() { return Err("open a document with data sets".into()); } - let mut params = json!({ - "commands": commands, - "label": a.name, - "source": source, - "destination": destination, - "overrideOpen": d.bool("overrideOpen"), - "overrideSave": d.bool("overrideSave"), - "overrideExport": d.bool("overrideExport"), - "stopOnError": d.bool("stopOnError"), - "includeSubdirs": d.bool("includeSubdirs"), - }); - if source == "folder" { - params["folder"] = json!(d.str("folder")); - } - if destination == "folder" { - params["destinationFolder"] = json!(d.str("destinationFolder")); - } + let params = params(d, &a.name, commands); let r = app.run("action.batch", params)?; app.ui.dialog = None; let count = r["count"].as_u64().unwrap_or(0); @@ -123,3 +117,76 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } Ok(r) } + +fn params(d: &Dialog, action_name: &str, commands: Vec) -> Value { + let source = d.str("source"); + let destination = d.str("destination"); + let mut params = json!({ + "commands": commands, + "label": action_name, + "source": source, + "destination": destination, + "overrideOpen": d.bool("overrideOpen"), + "overrideSave": d.bool("overrideSave"), + "overrideExport": d.bool("overrideExport"), + "stopOnError": d.bool("stopOnError"), + "includeSubdirs": d.bool("includeSubdirs"), + }); + if source == "folder" { + params["folder"] = json!(d.str("folder")); + } else if source == "datasets" { + params["datasetFileNaming"] = json!(d.str("datasetFileNaming")); + } + if destination == "folder" { + params["destinationFolder"] = json!(d.str("destinationFolder")); + } + params +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn shown(source: &str) -> Vec { + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), + _ => {} + } + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!(source); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut frame = ctx.run_ui(Default::default(), |ui| { + body(&mut app, ui, &mut d); + }); + frame.textures_delta.clear(); + let mut labels = vec![]; + frame.shapes.iter().for_each(|shape| collect(&shape.shape, &mut labels)); + labels + } + + #[test] + fn file_name_choice_shows_only_for_data_sets() { + assert!(shown("datasets").iter().any(|label| label == "File Name:")); + assert!(shown("datasets").iter().any(|label| label == "File + Number")); + assert!(!shown("folder").iter().any(|label| label == "File Name:")); + } + + #[test] + fn data_set_naming_params_follow_dialog_choice() { + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + assert_eq!(d.str("datasetFileNaming"), "fileNumber"); + d.fields["source"] = json!("datasets"); + for choice in ["fileNumber", "fileDataSetName", "dataSetName"] { + d.fields["datasetFileNaming"] = json!(choice); + assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], choice); + } + d.fields["source"] = json!("folder"); + assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index f9b5bf5584..c9071fd376 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -26,7 +26,7 @@ use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, PatternDef}; use super::brush_options::{clamped, mode_key, stroke_preview}; use crate::VectorcraftApp; @@ -44,6 +44,55 @@ const DIRECTIONS: [Direction; 4] = [Direction::LeftToRight, Direction::RightToLe const TILES: [(&str, &str); 5] = [("outer_corner", "outerCorner"), ("side", "side"), ("inner_corner", "innerCorner"), ("start", "start"), ("end", "end")]; +fn tile_key(field: &str) -> String { + match field { + "outer_corner" => "outerCornerTile".into(), + "inner_corner" => "innerCornerTile".into(), + _ => format!("{field}Tile"), + } +} + +pub(super) fn pattern_names(d: &Dialog) -> Vec { + d.fields + .get("__patterns") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_string)) + .collect() +} + +fn pattern_choice(d: &Dialog, choice: &str) -> Option { + let name = choice.strip_prefix("pattern:").unwrap_or(choice); + let reserved = choice == "none" || choice == "original" || CornerSource::parse(choice).is_some(); + (!reserved && pattern_names(d).iter().any(|candidate| candidate == name)).then(|| name.to_string()) +} + +pub(super) fn original_available(d: &Dialog, field: &str) -> bool { + let choice = d.str(&tile_key(field)); + let drawn = if field.ends_with("corner") { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; + drawn.is_some() && pattern_choice(d, &choice).is_none() +} + +pub(super) fn reconcile_pattern_choices(f: &mut Map) { + let names: Vec = f + .get("__patterns") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|v| v.get("name").and_then(Value::as_str).map(str::to_string)) + .collect(); + let def = f.get("__def").cloned().unwrap_or_default(); + for (art, _) in TILES { + let swatch = def.get(format!("{art}_swatch")).and_then(Value::as_str); + if let Some(name) = swatch.filter(|name| names.iter().any(|n| n == name)) { + f.insert(tile_key(art), json!(format!("pattern:{name}"))); + } else if !art.ends_with("corner") { + f.insert(tile_key(art), json!(if def.get(art).is_some_and(|v| !v.is_null()) { "original" } else { "none" })); + } + } +} + /// Pattern brush corner tiles: (dialog field, art field of the definition, source field, art field /// of the other kind of corner). const CORNER_TILES: [(&str, &str, &str, &str); 2] = @@ -63,20 +112,20 @@ fn corner_art_field<'a>(def: Option<&Value>, field: &'a str) -> Option<&'a str> } } -/// The dialog field that records that corner tile `key`'s menu was set. +/// The dialog field that records that tile `key`'s menu was set. fn corner_set_key(key: &str) -> String { format!("__{key}Set") } -/// Sets corner tile `key` to `choice` from its menu. +/// Sets tile `key` to `choice` from its menu. pub(super) fn choose_corner(d: &mut Dialog, key: &str, choice: &str) { d.fields.insert(key.into(), json!(choice)); note_set(d, key); } -/// Records that field `field` was set, from its menu or `ui.dialog.set`, when it is a corner tile. +/// Records that a tile field was set from its menu or `ui.dialog.set`. pub(super) fn note_set(d: &mut Dialog, field: &str) { - if CORNER_TILES.iter().any(|(key, ..)| *key == field) { + if CORNER_TILES.iter().any(|(key, ..)| *key == field) || TILES.iter().any(|(art, _)| tile_key(art) == field) { d.fields.insert(corner_set_key(field), json!(true)); } } @@ -259,18 +308,34 @@ pub(super) fn params(d: &Dialog) -> Value { let def = d.fields.get("__def"); for (key, art, source, other) in CORNER_TILES { let choice = d.str(key); + if let Some(name) = pattern_choice(d, &choice) { + if d.bool(&corner_set_key(key)) { + p[format!("{art}_tile")] = json!({"pattern": name}); + } + continue; + } let unset = |f: &str| def.and_then(|d| d.get(f)).is_none_or(Value::is_null); if choice == CornerSource::None.id() && !d.bool(&corner_set_key(key)) && unset(source) && corner_art_field(def, art).is_none() { continue; } if let Some(s) = CornerSource::parse(&choice) { - p[art] = Value::Null; - p[source] = json!(s.id()); + p[format!("{art}_tile")] = json!(s.id()); } else if choice == "original" && let Some(from) = corner_art_field(def, art).filter(|f| *f != art) && CORNER_TILES.iter().find(|(_, a, _, _)| *a == other).is_some_and(|(k, ..)| d.str(k) != "original") { p[art] = def.and_then(|d| d.get(from)).cloned().unwrap_or_default(); + p[format!("{art}_frame")] = def.and_then(|d| d.get(format!("{from}_frame"))).cloned().unwrap_or(Value::Null); + } + if choice == "original" && d.bool(&corner_set_key(key)) { + p[format!("{art}_tile")] = json!("original"); + } + } + for art in ["side", "start", "end"] { + let key = tile_key(art); + if d.bool(&corner_set_key(&key)) { + let choice = d.str(&key); + p[format!("{art}_tile")] = pattern_choice(d, &choice).map_or_else(|| json!(choice), |name| json!({"pattern": name})); } } p @@ -302,6 +367,35 @@ pub(super) fn edited_def(d: &Dialog) -> Value { if let (Some(o), Value::Object(p)) = (def.as_object_mut(), params(d)) { o.extend(p); } + if d.str("__type") == "pattern" { + for (art, _) in TILES { + let key = tile_key(art); + if !d.bool(&corner_set_key(&key)) { + continue; + } + let choice = d.str(&key); + if choice == "none" || (art.ends_with("corner") && CornerSource::parse(&choice).is_some()) { + def[art] = Value::Null; + def[format!("{art}_frame")] = Value::Null; + def[format!("{art}_swatch")] = Value::Null; + if art.ends_with("corner") { + def[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else if choice == "original" { + def[format!("{art}_swatch")] = Value::Null; + } else if let Some(name) = pattern_choice(d, &choice) + && let Some(pattern) = d.fields.get("__patterns").and_then(Value::as_array).and_then(|a| a.iter().find(|p| p["name"] == name)) + && let Ok(pattern) = serde_json::from_value::(pattern.clone()) + { + def[art] = serde_json::to_value(Node::new(NodeId(0), NodeKind::Group { children: pattern.art, clip: false })).unwrap_or_default(); + def[format!("{art}_frame")] = json!(pattern.tile); + def[format!("{art}_swatch")] = json!(name); + if art.ends_with("corner") { + def[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } def } @@ -447,12 +541,12 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { radios(ui, d, "fit", &fits); } -/// What a corner tile can be: (choice, label). Original (the corner art the brush draws there) is -/// offered only when the brush draws corner art there. +/// Built-in corner choices. Original is disabled when the slot has no retained art or a listed +/// swatch was selected. fn corner_choices() -> [(&'static str, &'static str); 6] { [ - ("original", tl!("Original")), (CornerSource::None.id(), tl!("None")), + ("original", tl!("Original")), (CornerSource::AutoCentered.id(), tl!("Auto-Centered")), (CornerSource::AutoBetween.id(), tl!("Auto-Between")), (CornerSource::AutoSliced.id(), tl!("Auto-Sliced")), @@ -460,31 +554,47 @@ fn corner_choices() -> [(&'static str, &'static str); 6] { ] } -/// The pattern's five tiles, each with its art (or None when the brush has no such tile). Below -/// each corner tile, a menu sets it to the brush's art, None or a tile made from the side tile. +pub(super) fn tile_choices(d: &Dialog, corner: bool) -> Vec<(String, String)> { + let mut choices: Vec<(String, String)> = if corner { + corner_choices().into_iter().map(|(id, label)| (id.into(), label.into())).collect() + } else { + vec![("none".into(), tl!("None").into()), ("original".into(), tl!("Original").into())] + }; + choices.extend(pattern_names(d).into_iter().map(|name| (format!("pattern:{name}"), name))); + choices +} + +/// The pattern's five tiles, each with its art (or None when the brush has no such tile). A menu +/// below each preview selects retained art, no art, or a document pattern; corners also offer +/// generated choices. fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let names = [tl!("Outer Corner Tile"), tl!("Side Tile"), tl!("Inner Corner Tile"), tl!("Start Tile"), tl!("End Tile")]; - let keys = d.fields.get("__tiles").cloned(); + let preview_def = edited_def(d); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; - for ((field, slot), name) in TILES.into_iter().zip(names) { + for ((field, _slot), name) in TILES.into_iter().zip(names) { let corner = CORNER_TILES.iter().find(|(_, art, _, _)| *art == field).map(|(key, ..)| *key); // The art the tile draws with: its own, or a corner's that falls back on the other's. - let drawn = if corner.is_some() { corner_art_field(d.fields.get("__def"), field) } else { Some(field) }; - let drawn_slot = drawn.and_then(|f| TILES.iter().find(|(tf, _)| *tf == f)).map_or(slot, |(_, s)| *s); - let choices: Vec<(&str, &str)> = corner_choices().into_iter().filter(|(c, _)| drawn.is_some() || *c != "original").collect(); - let choice = corner.map(|key| d.str(key)); + let drawn = if corner.is_some() { corner_art_field(Some(&preview_def), field) } else { Some(field) }; + let choice = d.str(&tile_key(field)); + let original_enabled = original_available(d, field); + let choices = tile_choices(d, corner.is_some()); // The label of the corner's choice when it shows no art. - let shown = choice.as_deref().filter(|c| *c != "original"); - let label = shown.and_then(|c| choices.iter().find(|(id, _)| *id == c)).map_or(tl!("None"), |(_, l)| *l); + let shown = (choice != "original" && pattern_choice(d, &choice).is_none()).then_some(choice.as_str()); + let label = shown.and_then(|c| choices.iter().find(|(id, _)| id == c)).map_or(tl!("None"), |(_, l)| l.as_str()); ui.vertical(|ui| { let (r, resp) = ui.allocate_exact_size(vec2(76.0, 44.0), Sense::hover()); ui.painter().rect_filled(r, 0.0, Color32::WHITE); - let key = keys.as_ref().filter(|_| shown.is_none()).and_then(|k| k.get(drawn_slot)).and_then(Value::as_str); - let tex = key.and_then(|key| { + let art_value = drawn.and_then(|f| preview_def.get(f)).filter(|_| shown.is_none()); + let key = art_value.map(|art| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + art.to_string().hash(&mut h); + format!("brush-tile:{:x}", h.finish()) + }); + let tex = key.as_deref().and_then(|key| { widgets::doc_preview(ui, key, r.size(), |w, h| { - let art: Node = serde_json::from_value(d.fields.get("__def")?.get(drawn?)?.clone()).ok()?; + let art: Node = serde_json::from_value(art_value?.clone()).ok()?; tile_doc(&art, w, h) }) }); @@ -499,14 +609,26 @@ fn tiles(ui: &mut egui::Ui, d: &mut Dialog) { ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); resp.on_hover_text(name); ui.add_sized(vec2(76.0, 14.0), egui::Label::new(egui::RichText::new(name).size(10.5).color(t.text_dim)).truncate()); - if let (Some(key), Some(cur)) = (corner, &choice) { - let current = choices.iter().find(|(id, _)| id == cur).map_or(tl!("None"), |(_, l)| *l); - let labels: Vec<&str> = choices.iter().map(|(_, l)| *l).collect(); - if let Some((id, _)) = - widgets::dropdown_named(ui, ("brush-pattern-corner", key), Some(name), current, &labels, 76.0).and_then(|i| choices.get(i)) - { - choose_corner(d, key, id); - } + let current = choices.iter().find(|(id, _)| id == &choice).map_or(tl!("None"), |(_, l)| l.as_str()); + if let Some(id) = widgets::combo_named(ui, ("brush-pattern-tile", field), Some(name), current, 76.0, |ui| { + choices.iter().enumerate().find_map(|(i, (id, label))| { + ui.add_enabled(id != "original" || original_enabled, egui::Button::selectable(id == &choice, label.as_str())) + .clicked() + .then_some(i) + }) + }) + .and_then(|i| choices.get(i).map(|(id, _)| id.clone())) + { + let key = corner.unwrap_or_else(|| { + if field == "side" { + "sideTile" + } else if field == "start" { + "startTile" + } else { + "endTile" + } + }); + choose_corner(d, key, &id); } }); } diff --git a/crates/ui-egui/src/dialogs/brush_delete.rs b/crates/ui-egui/src/dialogs/brush_delete.rs new file mode 100644 index 0000000000..52a86dc167 --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_delete.rs @@ -0,0 +1,90 @@ +//! The Brushes panel's Delete Brush question ([`ask`]): Yes or No when none of the brushes is in +//! use, else Remove Strokes or Cancel. Yes and Remove Strokes run `brush.delete`, which leaves the +//! strokes that used the brushes as plain strokes. +//! +//! Fields: `message` (the question, shown as the heading), `used` (whether a brush is in use), +//! `params` (the `brush.delete` params) and `__doc` (the uid of the document it asks about). + +use serde_json::{Value, json}; + +use super::{DialogAction, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; +use crate::widgets; + +/// The dialog kind of the Delete Brush question. +pub const KIND: &str = "brushDelete"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |d| d.str("message"), body_with_actions: Some(body), confirm, ok: None, max_width: Some(540.0), ..DialogSpec::FORM }; + +/// Ask whether to delete the brushes `params` names (`used`: one of them is in use). +pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) { + let message = if used { + tl!("Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes?") + } else { + tl!("Delete the selected brushes?") + }; + let doc = app.session.active().map(|d| d.uid); + app.ui.dialog = Some(Dialog::new(KIND, json!({"params": params, "used": used, "message": message, DOC: doc}))); +} + +/// The field that holds the uid of the document the question is about. +const DOC: &str = "__doc"; + +/// Whether a stroke uses one of `names` (`brush.unused`), or `None` when the query fails. +pub fn used(app: &mut VectorcraftApp, names: &[String]) -> Option { + let unused = app.run("brush.unused", json!({})).ok()?; + let unused = unused.get("names").and_then(Value::as_array).cloned().unwrap_or_default(); + Some(names.iter().any(|name| !unused.iter().any(|n| n.as_str() == Some(name)))) +} + +/// The brush names in `brush.delete` params (`name` or `names`). +fn names(params: &Value) -> Vec { + match params.get("name").and_then(Value::as_str) { + Some(name) => vec![name.to_string()], + None => params.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(), + } +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let mut action = DialogAction::None; + ui.horizontal(|ui| { + if d.bool("used") { + if widgets::primary_button_enabled(ui, tl!("Remove Strokes"), true).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("Cancel")).clicked() { + action = DialogAction::Cancel; + } + } else { + if widgets::primary_button_enabled(ui, tl!("Yes"), true).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button(ui, tl!("No")).clicked() { + action = DialogAction::Cancel; + } + } + }); + action +} + +/// Closes before running, so a dialog the command opens stays open. Yes on brushes that a stroke +/// has started to use since the question opened asks again with Remove Strokes and Cancel. When +/// another document has become the active one, it closes as Cancel does and deletes nothing. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = d.fields.get("params").cloned().unwrap_or_else(|| json!({})); + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } + if !d.bool("used") && used(app, &names(¶ms)) == Some(true) { + ask(app, params, true); + return Ok(json!({})); + } + app.ui.dialog = None; + app.run("brush.delete", params) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs new file mode 100644 index 0000000000..4092d63387 --- /dev/null +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -0,0 +1,106 @@ +use egui::{Pos2, Rect, pos2, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, time: f64) -> egui::FullOutput { + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let input = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out +} + +fn press(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, time: f64) { + frame(ctx, app, vec![], time); + let out = frame(ctx, app, vec![], time + 0.1); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("dialog accessibility tree").nodes; + let button = nodes.iter().find(|(_, node)| node.label().map(str::trim) == Some(label)); + let bounds = button.and_then(|(_, node)| node.bounds()).expect("visible button"); + let at = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], time + 0.2); +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx +} + +#[test] +fn visible_yes_and_no_buttons_control_unused_deletion() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let ctx = context(); + let before = app.session.active().unwrap().history.undo.len(); + ask(&mut app, json!({"name": name}), false); + press(&ctx, &mut app, "No", 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + assert!(app.run("brush.get", json!({"name": name})).is_ok()); + ask(&mut app, json!({"name": name}), false); + press(&ctx, &mut app, "Yes", 1.0); + assert!(app.run("brush.get", json!({"name": name})).is_err()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1); +} + +#[test] +fn yes_asks_again_when_a_stroke_started_using_the_brush() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = "10 pt. Oval"; + let ctx = context(); + ask(&mut app, json!({"names": [name]}), false); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); + app.run("brush.apply", json!({"name": name})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + press(&ctx, &mut app, "Yes", 0.0); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.bool("used")), "asks again with Remove Strokes"); + assert_eq!(app.session.active().unwrap().history.undo.len(), before); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), Some(name)); + press(&ctx, &mut app, "Remove Strokes", 1.0); + assert!(app.run("brush.get", json!({"name": name})).is_err()); +} + +#[test] +fn yes_deletes_nothing_after_another_document_became_active() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let name = app.run("brush.list", json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let ctx = context(); + ask(&mut app, json!({"name": name}), false); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + press(&ctx, &mut app, "Yes", 0.0); + assert!(app.ui.dialog.is_none()); + assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the second document keeps the brush"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.run("brush.get", json!({"name": name})).is_ok(), "the first document keeps the brush"); +} + +#[test] +fn visible_remove_strokes_and_cancel_buttons_control_used_deletion() { + for choice in ["Cancel", "Remove Strokes"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let name = "10 pt. Oval"; + app.run("brush.apply", json!({"name": name})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + let ctx = context(); + ask(&mut app, json!({"name": name}), true); + press(&ctx, &mut app, choice, 0.0); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice != "Cancel")); + let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); + assert_eq!(stroke.brush.as_deref(), (choice == "Cancel").then_some(name)); + assert!(stroke.width > 0.0); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index f03518b161..19a8e9c6e6 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -97,6 +97,10 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result Option { /// opens. pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) -> Result { let st = app.session.active().ok_or("no document open")?; + let patterns = serde_json::to_value(&st.doc.patterns).unwrap_or_default(); let title: String = ty.chars().take(1).flat_map(char::to_uppercase).chain(ty.chars().skip(1)).collect(); let name = vectorcraft_brush::unique_name(&vectorcraft_brush::library(&st.doc), &format!("New {title} Brush")); let mut def = json!({ "name": name, "type": ty }); @@ -169,6 +174,8 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) - b.sanitize(); let def = serde_json::to_value(&b).map_err(|e| e.to_string())?; let mut f = fields(&b, def)?; + f.insert("__patterns".into(), patterns); + brush_art_options::reconcile_pattern_choices(&mut f); f.insert(CREATE.into(), json!(true)); if let Some(ids) = ids { f.insert(IDS.into(), ids); @@ -183,9 +190,38 @@ pub(super) fn open_new(app: &mut VectorcraftApp, ty: &str, ids: Option) - /// dialog closes once the brush is made. fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut brush_params = params(d); + if d.str("__type") == "pattern" { + if d.str("sideTile") == "none" { + return Err("You must choose a side pattern.".into()); + } + let preview = brush_art_options::edited_def(d); + for key in [ + "side", + "side_frame", + "side_swatch", + "outer_corner", + "outer_corner_frame", + "outer_corner_swatch", + "outer_source", + "inner_corner", + "inner_corner_frame", + "inner_corner_swatch", + "inner_source", + "start", + "start_frame", + "start_swatch", + "end", + "end_frame", + "end_swatch", + ] { + if let Some(value) = preview.get(key) { + brush_params[key] = value.clone(); + } + } + } if let Some(def) = d.fields.get("__def") { for key in ["art", "side"] { - if let Some(art) = def.get(key).filter(|v| !v.is_null()) { + if let Some(art) = def.get(key).filter(|v| !v.is_null() && brush_params.get(key).is_none_or(Value::is_null)) { brush_params[key] = art.clone(); } } diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9adeffed1b..83fe73e3c1 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -458,7 +458,7 @@ fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() assert!(roles.contains(&egui::accesskit::Role::ComboBox), "a menu named {name}: {roles:?}"); } for name in ["Side Tile", "Start Tile", "End Tile"] { - assert!(!shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "no menu for {name}"); + assert!(shown_tree.iter().any(|n| n.label() == Some(name) && n.role() == egui::accesskit::Role::ComboBox), "a menu for {name}"); } set(&mut app, json!({"outerCornerTile": "autoBetween", "innerCornerTile": "autoOverlap"})); let text = shown(&mut app); @@ -492,6 +492,98 @@ fn pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile() assert_eq!(app.ui.dialog.as_ref().unwrap().str("outerCornerTile"), "autoSliced"); } +#[test] +fn pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let before = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(crate::dialogs::brush_art_options::pattern_names(d), vec!["Wide".to_string()]); + for key in ["sideTile", "outerCornerTile", "innerCornerTile", "startTile", "endTile"] { + assert!(d.fields.contains_key(key), "{key}"); + } + for corner in [false, true] { + let ids: Vec<_> = crate::dialogs::brush_art_options::tile_choices(d, corner).into_iter().map(|(id, _)| id).collect(); + assert!(ids.contains(&"pattern:Wide".to_string())); + if corner { + for auto in ["autoCentered", "autoBetween", "autoSliced", "autoOverlap"] { + assert!(ids.contains(&auto.to_string())); + } + } else { + assert_eq!(ids.first().map(String::as_str), Some("none")); + assert_eq!(ids.get(1).map(String::as_str), Some("original")); + } + } + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "Wide"); + assert!(!crate::dialogs::brush_art_options::original_available(d, "side")); + let preview = crate::dialogs::brush_art_options::edited_def(d); + assert_eq!(preview["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + assert_ne!(preview["side"], before["side"]); + super::super::confirm(&mut app).unwrap(); + app.session + .edit("Delete pattern", |doc, _| { + doc.patterns.clear(); + Ok(()) + }) + .unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sideTile"), "original"); + let saved = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "none"); + let error = super::super::confirm(&mut app).unwrap_err(); + assert!(error.contains("You must choose a side pattern."), "{error}"); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.run("brush.get", json!({"name":"Diamonds"})).unwrap(), saved); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn new_pattern_brush_keeps_a_tile_swatch_choice() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.run("shape.rectangle", json!({"x":0,"y":0,"width":20,"height":4})).unwrap(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Wide", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + super::open_new(&mut app, "pattern", None).unwrap(); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, "sideTile", "Wide"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name":name})).unwrap(); + assert_eq!(def["side_swatch"], "Wide"); + assert_eq!(def["side_frame"], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); +} + /// A pattern brush with art for one kind of corner draws it at both kinds. Its other corner tile /// shows that art as Original, and OK keeps it there when the first corner tile changes. #[test] @@ -509,6 +601,115 @@ fn pattern_options_keep_the_corner_art_a_corner_borrows() { assert_eq!(def["outer_source"], json!("none")); } +#[test] +fn pattern_options_preview_and_save_borrowed_corner_before_clearing_source() { + use vectorcraft_geom::Rect; + + let mut app = app(); + let chain = app.run("brush.get", json!({"name": "Chain"})).unwrap(); + let art = chain["outer_corner"].clone(); + let frame = json!(Rect::new(1.0, 2.0, 15.0, 18.0)); + for (name, source, borrowed) in [("Borrow Outer", "inner", "outer"), ("Borrow Inner", "outer", "inner")] { + let source_art = format!("{source}_corner"); + let source_frame = format!("{source_art}_frame"); + let borrowed_art = format!("{borrowed}_corner"); + let borrowed_frame = format!("{borrowed_art}_frame"); + let source_tile = format!("{source}CornerTile"); + let borrowed_tile = format!("{borrowed}CornerTile"); + app.run("brush.new", json!({"type":"pattern", "name":name, "params":{"side":chain["side"], source_art:art, source_frame:frame}})).unwrap(); + app.run("ui.brushOptions", json!({"name":name})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::brush_art_options::choose_corner(d, &source_tile, "none"); + crate::dialogs::brush_art_options::choose_corner(d, &borrowed_tile, "original"); + let preview = crate::dialogs::brush_art_options::edited_def(d); + assert_eq!(preview[&borrowed_art], chain["outer_corner"], "{borrowed} preview art"); + assert_eq!(preview[&borrowed_frame], frame, "{borrowed} preview frame"); + super::super::confirm(&mut app).unwrap(); + let saved = app.run("brush.get", json!({"name":name})).unwrap(); + assert_eq!(saved[&borrowed_art], chain["outer_corner"], "{borrowed} saved art"); + assert_eq!(saved[&borrowed_frame], frame, "{borrowed} saved frame"); + } +} + +#[test] +fn pattern_options_borrowed_swatch_corner_keeps_its_frame() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + app.session + .edit("Pattern", |doc, _| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new("Corner", vec![Arc::new(art)]) }); + Ok(()) + }) + .unwrap(); + let side = app.run("brush.get", json!({"name":"Diamonds"})).unwrap()["side"].clone(); + app.run("brush.new", json!({"type":"pattern", "name":"Borrow", "params":{"side":side}})).unwrap(); + app.run("brush.options", json!({"name":"Borrow", "params":{"outer_corner_tile":{"pattern":"Corner"}}})).unwrap(); + let before = app.run("brush.get", json!({"name":"Borrow"})).unwrap(); + app.run("ui.brushOptions", json!({"name":"Borrow"})).unwrap(); + set(&mut app, json!({"outerCornerTile":"none"})); + super::super::confirm(&mut app).unwrap(); + let after = app.run("brush.get", json!({"name":"Borrow"})).unwrap(); + assert_eq!(after["inner_corner"], before["outer_corner"]); + assert_eq!(after["inner_corner_frame"], before["outer_corner_frame"]); + assert_eq!(after["outer_source"], json!("none")); +} + +#[test] +fn pattern_options_selects_swatches_with_reserved_names() { + use std::sync::Arc; + use vectorcraft_doc::{Node, PatternDef}; + use vectorcraft_geom::Rect; + + let mut app = app(); + let names = ["none", "original", "autoCentered", "autoBetween", "autoSliced", "autoOverlap"]; + app.session + .edit("Patterns", |doc, _| { + for name in names { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 4.0)), + vectorcraft_doc::Appearance::default_art(), + ); + doc.patterns.push(PatternDef { tile: Rect::new(0.0, 0.0, 10.0, 4.0), ..PatternDef::new(name, vec![Arc::new(art)]) }); + } + Ok(()) + }) + .unwrap(); + app.run("ui.brushOptions", json!({"name":"Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + for name in names { + let choice = (format!("pattern:{name}"), name.to_string()); + assert!(crate::dialogs::brush_art_options::tile_choices(d, true).contains(&choice)); + } + for (field, name) in [ + ("sideTile", "none"), + ("outerCornerTile", "original"), + ("innerCornerTile", "autoCentered"), + ("startTile", "autoBetween"), + ("endTile", "autoSliced"), + ] { + crate::dialogs::brush_art_options::choose_corner(app.ui.dialog.as_mut().unwrap(), field, &format!("pattern:{name}")); + } + let preview = crate::dialogs::brush_art_options::edited_def(app.ui.dialog.as_ref().unwrap()); + assert_eq!(preview["side_swatch"], "none"); + super::super::confirm(&mut app).unwrap(); + let saved = app.run("brush.get", json!({"name":"Diamonds"})).unwrap(); + for (art, name) in + [("side", "none"), ("outer_corner", "original"), ("inner_corner", "autoCentered"), ("start", "autoBetween"), ("end", "autoSliced")] + { + assert_eq!(saved[format!("{art}_swatch")], name); + assert_eq!(saved[format!("{art}_frame")], json!(Rect::new(0.0, 0.0, 10.0, 4.0))); + } +} + /// OK leaves the corner fields of a corner tile the menus were not set to as they were: a corner /// without art keeps borrowing the other kind's art when it gets some, and a corner that borrows /// art still borrows it. A None picked from the menu is saved, after another choice too. diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs new file mode 100644 index 0000000000..848151ac54 --- /dev/null +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -0,0 +1,548 @@ +//! Character Style Options fields shared by editing and creating a character style. + +use serde_json::{Map, Value, json}; + +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +pub const KIND: &str = "charStyleOptions"; +const BASIC: &[&str] = &[ + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "all_caps", + "small_caps", + "position", + "underline", + "strikethrough", + "charAlign", +]; +const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Character Style Options").into(), + body, + confirm, + preview: true, + inputs: |_| { + &[ + "name", + "font_family", + "font_style", + "size", + "leading", + "kerning", + "tracking", + "case", + "position", + "underline", + "strikethrough", + "charAlign", + "section", + ] + }, + min_width: 650.0, + ..DialogSpec::FORM +}; + +pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { + crate::panels::character::end_typing(app); + let doc = &app.session.active().ok_or("no document open")?.doc; + let def = doc.char_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no character style `{name}`"))?; + let mut fields = fields_from_attrs(&def.attrs); + fields.insert("name".into(), json!(name)); + fields.insert("__style".into(), json!(name)); + fields.insert("__attrs".into(), json!(def.attrs)); + fields.insert("__smallCapsSize".into(), json!(doc.setup.small_caps_size)); + fields.insert("__superscript".into(), json!(doc.setup.superscript)); + fields.insert("__subscript".into(), json!(doc.setup.subscript)); + fields.insert("section".into(), json!("general")); + fields.insert("preview".into(), json!(true)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({"dialog": KIND})) +} + +pub(crate) fn fields_from_attrs(attrs: &Map) -> Map { + let mut fields = Map::new(); + for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "underline", "strikethrough", "charAlign"] { + let value = attrs.get(key).cloned().unwrap_or(Value::Null); + let shown = if ["underline", "strikethrough"].contains(&key) { + value + } else if value.is_null() { + if attrs.contains_key(key) && ["leading", "kerning"].contains(&key) { json!("Auto") } else { json!("") } + } else { + value + }; + fields.insert(key.into(), shown); + } + fields.insert("case".into(), case_from_attrs(attrs).map_or(Value::Null, Value::from)); + fields.insert("position".into(), attrs.get("position").and_then(|v| v.get("kind")).cloned().unwrap_or(Value::Null)); + fields +} + +fn case_from_attrs(attrs: &Map) -> Option<&'static str> { + if attrs.get("all_caps") == Some(&json!(true)) { + Some("allCaps") + } else if attrs.get("small_caps").is_some_and(|v| !v.is_null()) { + Some("smallCaps") + } else if attrs.contains_key("all_caps") || attrs.contains_key("small_caps") { + Some("normal") + } else { + None + } +} + +fn optional_number(d: &Dialog, key: &str) -> Result, String> { + let label = match key { + "size" => tl!("Size"), + "leading" => tl!("Leading"), + "kerning" => tl!("Kerning"), + "tracking" => tl!("Tracking"), + _ => return Err("unknown character style number field".into()), + }; + match d.fields.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if s.trim().is_empty() => Ok(None), + Some(Value::String(s)) if s.trim().eq_ignore_ascii_case("auto") && ["leading", "kerning"].contains(&key) => Ok(Some(Value::Null)), + Some(v) => { + let n = v + .as_f64() + .or_else(|| v.as_str().and_then(|s| s.trim().parse::().ok())) + .filter(|n| n.is_finite()) + .ok_or_else(|| format!("{label} must be a number"))?; + if ["size", "leading"].contains(&key) && n < 0.1 { + return Err(format!("{label} must be a number of at least 0.1")); + } + Ok(Some(json!(n))) + } + } +} + +pub(crate) fn edited_attrs(d: &Dialog) -> Result, String> { + let original = d.fields.get("__attrs").and_then(Value::as_object).cloned().unwrap_or_default(); + let original_fields = fields_from_attrs(&original); + let reset = d.bool("__resetBasic"); + let mut attrs = original.clone(); + for key in BASIC { + attrs.remove(*key); + } + for key in ["font_family", "font_style"] { + if let Some(v) = d.fields.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { + attrs.insert(key.into(), json!(v.trim())); + } + } + if reset || ["font_family", "font_style"].iter().any(|key| d.fields.get(*key) != original_fields.get(*key)) { + attrs.remove("font_version"); + attrs.remove("fontAxes"); + } + for key in NUMBERS { + if let Some(v) = optional_number(d, key)? { + attrs.insert((*key).into(), v); + } + } + for key in ["underline", "strikethrough"] { + if let Some(v) = d.fields.get(key).and_then(Value::as_bool) { + attrs.insert(key.into(), json!(v)); + } + } + if reset || d.fields.get("case").and_then(Value::as_str) != case_from_attrs(&original) { + match d.fields.get("case").and_then(Value::as_str) { + Some("allCaps") => { + attrs.insert("all_caps".into(), json!(true)); + attrs.insert("small_caps".into(), Value::Null); + } + Some("smallCaps") => { + attrs.insert("all_caps".into(), json!(false)); + attrs.insert( + "small_caps".into(), + original + .get("small_caps") + .filter(|v| v.is_number()) + .cloned() + .unwrap_or_else(|| d.fields.get("__smallCapsSize").cloned().unwrap_or_else(|| json!(70.0))), + ); + } + Some("normal") => { + attrs.insert("all_caps".into(), json!(false)); + attrs.insert("small_caps".into(), Value::Null); + } + _ => {} + } + } + if let Some(position) = d.fields.get("position").and_then(Value::as_str).filter(|v| !v.is_empty()) { + let value = if position == "normal" { + json!({"kind": "normal"}) + } else { + original.get("position").filter(|v| v.get("kind").and_then(Value::as_str) == Some(position)).cloned().unwrap_or_else(|| { + let metrics = d.fields.get(if position == "superscript" { "__superscript" } else { "__subscript" }); + json!({"kind": position, "size": metrics.and_then(|m| m.get("size")).cloned().unwrap_or(json!(58.3)), + "position": metrics.and_then(|m| m.get("position")).cloned().unwrap_or(json!(33.3))}) + }) + }; + attrs.insert("position".into(), value); + } + if let Some(align) = d.fields.get("charAlign").and_then(Value::as_str).filter(|v| !v.is_empty()) { + attrs.insert("charAlign".into(), json!(align)); + } + if !reset { + for key in BASIC { + let field = if ["all_caps", "small_caps"].contains(key) { "case" } else { key }; + if d.fields.get(field) == original_fields.get(field) { + attrs.remove(*key); + if let Some(value) = original.get(*key) { + attrs.insert((*key).into(), value.clone()); + } + } + } + } + Ok(attrs) +} + +pub(crate) fn reset_basic(d: &mut Dialog) { + d.fields.insert("__resetBasic".into(), json!(true)); + for key in ["font_family", "font_style", "size", "leading", "kerning", "tracking", "case", "position", "underline", "strikethrough", "charAlign"] + { + d.fields.insert( + key.into(), + if ["font_family", "font_style", "size", "leading", "kerning", "tracking"].contains(&key) { json!("") } else { Value::Null }, + ); + } +} + +pub fn reset_panel(app: &mut VectorcraftApp) -> Result { + let d = app.ui.dialog.as_mut().ok_or("no dialog open")?; + let character_new = d.kind == super::new_text_style::KIND && !d.bool("__para"); + if (d.kind != KIND && !character_new) || d.str("section") != "basic" { + return Err("the open dialog has no Reset".into()); + } + reset_basic(d); + Ok(json!({"dialog": d.kind})) +} + +fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)]) { + let selected = d.fields.get(key).and_then(Value::as_str).unwrap_or("").to_string(); + let shown = options.iter().find(|(value, _)| *value == selected).map_or("", |(_, label)| *label); + let labels: Vec<&str> = std::iter::once(" ").chain(options.iter().map(|(_, label)| *label)).collect(); + if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, 190.0) { + d.fields.insert(key.into(), if i == 0 { Value::Null } else { options.get(i - 1).map_or(Value::Null, |(value, _)| json!(value)) }); + } +} + +pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { + egui::Grid::new("character-style-basic").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { + for (key, caption) in [ + ("font_family", tl!("Font Family:")), + ("font_style", tl!("Font Style:")), + ("size", tl!("Size")), + ("leading", tl!("Leading")), + ("kerning", tl!("Kerning")), + ("tracking", tl!("Tracking")), + ] { + ui.label(caption); + if d.fields.get(key).is_some_and(Value::is_null) { + d.fields.insert(key.into(), json!("")); + } + form::text(ui, d, key, 190.0); + ui.end_row(); + } + ui.label(tl!("Case")); + choice(ui, d, "case", &[("normal", tl!("Normal")), ("allCaps", tl!("All Caps")), ("smallCaps", tl!("Small Caps"))]); + ui.end_row(); + ui.label(tl!("Position")); + choice(ui, d, "position", &[("normal", tl!("Normal")), ("superscript", tl!("Superscript")), ("subscript", tl!("Subscript"))]); + ui.end_row(); + for (key, caption) in [("underline", tl!("Underline")), ("strikethrough", tl!("Strikethrough"))] { + ui.label(""); + let value = d.fields.get(key).and_then(Value::as_bool); + if crate::widgets::check3(ui, caption, value, true) { + d.fields.insert( + key.into(), + match value { + None => json!(true), + Some(true) => json!(false), + Some(false) => Value::Null, + }, + ); + } + ui.end_row(); + } + ui.label(tl!("Standard Vertical Roman Alignment")); + choice( + ui, + d, + "charAlign", + &[ + ("romanBaseline", tl!("Roman Baseline")), + ("emBoxTop", tl!("Em Box Top/Right")), + ("emBoxCenter", tl!("Em Box Center")), + ("emBoxBottom", tl!("Em Box Bottom/Left")), + ("icfTop", tl!("ICF Top/Right")), + ("icfBottom", tl!("ICF Bottom/Left")), + ], + ); + ui.end_row(); + }); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (id, label) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats"))] { + if ui.selectable_label(d.str("section") == id, label).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); + ui.separator(); + ui.vertical(|ui| { + if d.str("section") == "basic" { + basic_body(ui, d); + } else { + ui.horizontal(|ui| { + ui.label(tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + }); + ui.separator(); + if let Ok(attrs) = edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } + } + }); + }); + ui.add_enabled_ui(d.str("section") == "basic", |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + reset_basic(d); + } + }); + match edited_attrs(d) { + Ok(attrs) => { + let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); + form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); + } + Err(why) => { + ui.add_space(6.0); + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), &why)); + } + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let attrs = edited_attrs(d)?; + form::commit_preview(app, "charStyle.edit", json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs})) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app + } + + fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + } + + #[test] + fn unchanged_basic_fields_preserve_original_keys() { + for attrs in [ + json!({"all_caps": false}), + json!({"all_caps": true}), + json!({"small_caps": 70.0}), + json!({"font_family": "Example", "font_style": "Regular", "font_version": "1", "size": 24, + "leading": null, "kerning": null, "tracking": 3, "underline": null, + "strikethrough": false, "position": {"kind": "normal", "size": 80}, "charAlign": null}), + ] { + let original = attrs.as_object().unwrap().clone(); + let mut fields = fields_from_attrs(&original); + fields.insert("__attrs".into(), attrs); + let d = Dialog { kind: KIND.into(), fields }; + assert_eq!(edited_attrs(&d).unwrap(), original); + } + let original = json!({"all_caps": false}).as_object().unwrap().clone(); + let mut fields = fields_from_attrs(&original); + fields.insert("__attrs".into(), json!(original)); + fields.insert("case".into(), json!("allCaps")); + let d = Dialog { kind: KIND.into(), fields }; + assert_eq!(edited_attrs(&d).unwrap(), json!({"all_caps": true, "small_caps": null}).as_object().unwrap().clone()); + } + + #[test] + fn unchanged_options_keep_local_small_caps_and_history() { + for preview in [false, true] { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"all_caps": false}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 4, "smallCaps": true})).unwrap(); + let state = app.session.doc().unwrap(); + let before = state.doc.clone(); + let history = (state.history.undo.len(), state.history.redo.len()); + open(&mut app, "Body").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(preview)); + if preview { + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.doc, before); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!( + state.doc.node(vectorcraft_doc::NodeId(id)).and_then(|node| match &node.kind { + vectorcraft_doc::NodeKind::Text(text) => text.runs.first().map(|run| run.style.small_caps), + _ => None, + }), + Some(Some(state.doc.setup.small_caps_size)) + ); + } + } + + #[test] + fn options_preview_cancel_reset_and_commit_keep_sparse_definition() { + let mut app = app(); + app.run("charStyle.new", json!({"name":"Body","attrs":{"size":24.0,"baseline_shift":3.0}})).unwrap(); + let id = app.run("text.create", json!({"x":10,"y":40,"text":"Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name":"Body","id":id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + open(&mut app, "Body").unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("preview")); + assert!(app.run("ui.charStyleOptions.resetPanel", json!({})).is_err()); + assert!(app.ui.dialog.as_ref().unwrap().fields["underline"].is_null()); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("kerning"), ""); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert("size".into(), json!(18)); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].name, "Revised"); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("basic")); + } + app.run("ui.charStyleOptions.resetPanel", json!({})).unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(edited_attrs(d).unwrap(), serde_json::from_value(json!({"baseline_shift":3.0})).unwrap()); + d.fields.insert("name".into(), json!("Revised")); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.history.undo.len(), undo + 1); + assert_eq!(state.doc.char_styles[0].name, "Revised"); + assert_eq!(state.doc.char_styles[0].attrs, serde_json::from_value(json!({"baseline_shift":3.0})).unwrap()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].name, "Revised"); + app.run("select.set", json!({"ids":[id]})).unwrap(); + app.run("ui.newCharStyle", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("size"), "12.0"); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("size".into(), json!(36.0)); + d.fields.insert("name".into(), json!("Future")); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles.iter().find(|def| def.name == "Future").unwrap().attrs["size"], json!(36.0)); + } + + #[test] + fn invalid_numbers_name_the_visible_field() { + let mut d = Dialog::new(KIND, json!({})); + for (key, label) in [("size", "Size"), ("leading", "Leading"), ("kerning", "Kerning"), ("tracking", "Tracking")] { + d.fields.insert(key.into(), json!("not a number")); + assert_eq!(optional_number(&d, key).unwrap_err(), format!("{label} must be a number")); + } + } + + #[test] + fn size_and_leading_below_minimum_do_not_preview_or_commit() { + for (key, value) in [("size", json!(0)), ("size", json!(-2)), ("leading", json!(0.09)), ("leading", json!(-1))] { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0, "leading": 28.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert(key.into(), value); + assert!(edited_attrs(d).unwrap_err().contains("at least 0.1")); + } + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before, "{key} preview"); + assert!(super::super::confirm(&mut app).is_err(), "{key} confirm"); + assert_eq!(app.session.doc().unwrap().doc, before, "{key} confirm"); + } + } + + #[test] + fn invalid_number_keeps_last_valid_preview() { + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + open(&mut app, "Body").unwrap(); + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("name".into(), json!("Revised")); + d.fields.insert("size".into(), json!(18)); + } + frame(&mut app); + let valid = app.session.doc().unwrap().doc.clone(); + assert_eq!(valid.char_styles[0].name, "Revised"); + assert_eq!(valid.char_styles[0].attrs["size"], json!(18.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("size".into(), json!("invalid")); + frame(&mut app); + assert_eq!(app.session.doc().unwrap().doc, valid); + } + + #[test] + fn script_positions_use_document_setup_in_existing_and_new_style_dialogs() { + let mut app = app(); + app.run( + "document.setup", + json!({"superscript": {"size": 67.0, "position": 22.0}, + "subscript": {"size": 72.0, "position": 18.0}}), + ) + .unwrap(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + open(&mut app, "Body").unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("position".into(), json!("superscript")); + assert_eq!( + edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["position"], + json!({"kind": "superscript", "size": 67.0, "position": 22.0}) + ); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs["position"], json!({"kind": "superscript", "size": 67.0, "position": 22.0})); + app.run("ui.newCharStyle", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("position".into(), json!("subscript")); + assert_eq!(edited_attrs(app.ui.dialog.as_ref().unwrap()).unwrap()["position"], json!({"kind": "subscript", "size": 72.0, "position": 18.0})); + super::super::confirm(&mut app).unwrap(); + assert_eq!( + app.session.doc().unwrap().doc.char_styles.last().unwrap().attrs["position"], + json!({"kind": "subscript", "size": 72.0, "position": 18.0}) + ); + } +} diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 16fa10bea8..205e4fa98e 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -337,19 +337,21 @@ pub(super) fn progress(ui: &mut egui::Ui, d: &Dialog) { widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), e)); } if let Some(s) = d.fields.get("searched") { - let (folders, files) = (s["folders"].to_string(), s["files"].to_string()); - widgets::dim_name( - ui, - &crate::i18n::fmt(tl!("{folders} folder(s) and {files} file(s) searched"), &[("folders", &folders), ("files", &files)]), - ); + let folders = crate::i18n::tn(s["folders"].as_u64().unwrap_or(0), "{n} folder", "{n} folders"); + let files = crate::i18n::tn(s["files"].as_u64().unwrap_or(0), "{n} file", "{n} files"); + widgets::dim_name(ui, &crate::i18n::fmt(tl!("{folders} and {files} searched"), &[("folders", &folders), ("files", &files)])); } - let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0).map(|n| n.to_string()); + let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0); if let Some(n) = count("skipped") { - let text = tl!("{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones"); - widgets::dim_name(ui, &crate::i18n::fmt(text, &[("count", &n)])); + let text = crate::i18n::tn( + n, + "{n} folder skipped, such as another app's or the system's folder or a hidden one", + "{n} folders skipped, such as other apps' and the system's folders and hidden ones", + ); + widgets::dim_name(ui, &text); } if let Some(n) = count("unreadable") { - widgets::dim_name(ui, &crate::i18n::fmt(tl!("{count} folder(s) or file(s) couldn't be read"), &[("count", &n)])); + widgets::dim_name(ui, &crate::i18n::tn(n, "{n} folder or file couldn't be read", "{n} folders or files couldn't be read")); } if matches!(d.fields.get("stopped").and_then(Value::as_str), Some("time" | "limit")) { widgets::dim_label(ui, tl!("The search stopped at its limit: search a smaller folder.")); diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 20266d97b3..c2b2a4e6c8 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -328,6 +328,29 @@ fn files_go_with_their_fonts_by_name() { assert_eq!((d.str("state"), &d.fields["chosen"]), ("done".to_string(), &json!([]))); } +/// A folder search's counts use the forms the language's plural rule picks for each count. +#[test] +fn search_counts_use_each_count_form() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut progress_text = |code: &str, n: u64| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let d = Dialog::new(KIND, json!({"state": "done", "searched": {"folders": n, "files": n}, "unreadable": n})); + let text = crate::tests_labels::painted_text(&mut app, |_, ui| progress(ui, &d)); + crate::i18n::set_current(crate::i18n::Lang::EN); + text + }; + let text = progress_text("en", 1); + assert!(text.contains("1 folder and 1 file searched") && text.contains("1 folder or file couldn't be read"), "{text}"); + for (n, searched, unreadable) in [ + (1, "Prohledáno: 1 složka, 1 soubor", "Nepodařilo se přečíst 1 složku nebo soubor"), + (2, "Prohledáno: 2 složky, 2 soubory", "Nepodařilo se přečíst 2 složky nebo soubory"), + (5, "Prohledáno: 5 složek, 5 souborů", "Nepodařilo se přečíst 5 složek nebo souborů"), + ] { + let text = progress_text("cs", n); + assert!(text.contains(searched) && text.contains(unreadable), "{n}: {text}"); + } +} + #[test] fn the_web_says_how_many_fonts_are_missing() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index b717057698..fe6a804860 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -75,17 +75,23 @@ pub(super) fn ask_next(app: &mut VectorcraftApp, rest: Vec, modified: Vec /// With Update Links: Ask When Modified, offer to read the modified linked files `ids` again. fn ask_update(app: &mut VectorcraftApp, ids: Vec) { - ask(app, ids, tl!("{count} linked image(s) changed since this document was saved. Show the new versions?")); + ask( + app, + ids, + "{n} linked image changed since this document was saved. Show the new version?", + "{n} linked images changed since this document was saved. Show the new versions?", + ); } /// The same offer for linked files another app changed while the document is open /// ([`vectorcraft_engine::link_watch`]). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn ask_update_changed(app: &mut VectorcraftApp, ids: Vec) { - ask(app, ids, tl!("{count} linked image(s) changed on disk. Show the new versions?")); + ask(app, ids, "{n} linked image changed on disk. Show the new version?", "{n} linked images changed on disk. Show the new versions?"); } -fn ask(app: &mut VectorcraftApp, ids: Vec, question: &str) { +/// Ask about the modified linked files `ids`; `one` and `other` are the English forms of the question. +fn ask(app: &mut VectorcraftApp, ids: Vec, one: &str, other: &str) { if ids.is_empty() { return; } @@ -93,7 +99,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec, question: &str) { app.status(format!("{} linked image(s) changed on disk: Update Links shows the new versions", ids.len())); return; } - let detail = crate::i18n::fmt(question, &[("count", &ids.len().to_string())]); + let detail = crate::i18n::tn(ids.len() as u64, one, other); super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids })); } @@ -133,7 +139,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if rest > 0 { ui.add_space(10.0); let all = d.bool("applyToAll"); - let label = crate::i18n::fmt(tl!("Apply to All ({count} more missing)"), &[("count", &rest.to_string())]); + let label = crate::i18n::tn(rest as u64, "Apply to All ({n} more missing)", "Apply to All ({n} more missing)"); if widgets::check(ui, &label, all, true) { d.fields.insert("applyToAll".into(), json!(!all)); } @@ -262,6 +268,24 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// The question about modified linked files uses the form the language's plural rule picks for + /// the count. + #[test] + fn the_modified_links_question_uses_each_count_form() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut question = |code: &str, n: u64| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + ask_update(&mut app, (0..n).map(|id| json!(id)).collect()); + let detail = app.ui.dialog.take().map(|d| d.str("detail")); + crate::i18n::set_current(crate::i18n::Lang::EN); + detail.unwrap_or_default() + }; + assert_eq!(question("en", 1), "1 linked image changed since this document was saved. Show the new version?"); + assert_eq!(question("cs", 1), "Od uložení dokumentu se změnil 1 propojený obrázek. Zobrazit novou verzi?"); + assert_eq!(question("cs", 2), "Od uložení dokumentu se změnily 2 propojené obrázky. Zobrazit nové verze?"); + assert_eq!(question("cs", 5), "Od uložení dokumentu se změnilo 5 propojených obrázků. Zobrazit nové verze?"); + } + #[test] fn apply_to_all_replaces_the_others_from_the_same_folder() { let (mut app, dir, _) = opened_without_links("all"); diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index b585b2e145..0303db8c6f 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -57,7 +57,8 @@ pub(crate) fn drag_band(ui: &mut egui::Ui, bottom: f32) { // Last frame's rectangle: none while the window measures itself the first time it shows. let Some(outer) = ui.ctx().memory(|m| m.area_rect(id)) else { return }; let band = Rect::from_x_y_ranges(outer.x_range(), outer.top()..=bottom.max(outer.top())); - let r = ui.interact(band, handle(id), egui::Sense::drag()); + // Not focusable (`Sense::drag()` is): Tab goes through the dialog's controls, not the band. + let r = ui.interact(band, handle(id), egui::Sense::DRAG); if r.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); } else if r.hovered() { @@ -66,7 +67,7 @@ pub(crate) fn drag_band(ui: &mut egui::Ui, bottom: f32) { } /// The drag handle of window `id`. -fn handle(id: Id) -> Id { +pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index f945332e64..16ec9568d5 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -31,14 +31,60 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result bool { + if !para(d) { + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (id, title) in [("general", tl!("General")), ("basic", tl!("Basic Character Formats"))] { + if ui.selectable_label(d.str("section") == id, title).clicked() { + d.fields.insert("section".into(), json!(id)); + } + } + }); + ui.separator(); + if d.str("section") == "basic" { + super::char_style_options::basic_body(ui, d); + } else { + ui.vertical(|ui| { + grid(ui, |ui| { + label(ui, tl!("Style Name:")); + form::text(ui, d, "name", 190.0); + ui.end_row(); + }); + if let Ok(attrs) = super::char_style_options::edited_attrs(d) { + for (key, value) in attrs { + ui.label(format!("{}: {}", super::humanize(&key), value)); + } + } + }); + } + }); + ui.add_enabled_ui(d.str("section") == "basic", |ui| { + if ui.button(tl!("Reset Panel")).clicked() { + super::char_style_options::reset_basic(d); + } + }); + return false; + } grid(ui, |ui| { label(ui, tl!("Style Name:")); form::text(ui, d, "name", 190.0); @@ -52,6 +98,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut params = d.fields.get("__target").filter(|t| t.is_object()).cloned().unwrap_or_else(|| json!({})); params["name"] = json!(d.str("name")); + if !para(d) { + params["attrs"] = Value::Object(super::char_style_options::edited_attrs(d)?); + } let r = app.run(if para(d) { "paraStyle.new" } else { "charStyle.new" }, params); if let Ok(v) = &r { app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 839f763835..2cc994be40 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -155,32 +155,25 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later // The fonts left out: their license doesn't allow it, or they aren't on this computer. let fonts = r["skippedFonts"].as_array().into_iter().flatten().filter_map(|f| f["font"].as_str()).collect::>().join(", "); let shown_note = package_status_note(missing, &fonts); - let n_s = n.to_string(); + let n = n as u64; if web { let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; - let status = if shown_note.is_empty() { - crate::i18n::fmt(tl!("Packaged {n} file(s)"), &[("n", &n_s)]) - } else { - crate::i18n::fmt(tl!("Packaged {n} file(s) {note}"), &[("n", &n_s), ("note", &shown_note)]) - }; - app.status(status); + app.status(package_status(n, None, &shown_note)); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); - let status = if shown_note.is_empty() { - crate::i18n::fmt(tl!("Packaged {n} file(s) in {folder}"), &[("n", &n_s), ("folder", &folder)]) - } else { - crate::i18n::fmt(tl!("Packaged {n} file(s) in {folder} {note}"), &[("n", &n_s), ("folder", &folder), ("note", &shown_note)]) - }; - app.status(status); + app.status(package_status(n, Some(&folder), &shown_note)); let detail = if shown_note.is_empty() { - crate::i18n::fmt(tl!("{count} file(s) in {folder}. Show the package folder?"), &[("count", &n_s), ("folder", &folder)]) + crate::i18n::fmt( + &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), + &[("folder", &folder)], + ) } else { crate::i18n::fmt( - tl!("{count} file(s) in {folder} {note}. Show the package folder?"), - &[("count", &n_s), ("folder", &folder), ("note", &shown_note)], + &crate::i18n::tn(n, "{n} file in {folder} {note}. Show the package folder?", "{n} files in {folder} {note}. Show the package folder?"), + &[("folder", &folder), ("note", &shown_note)], ) }; if app.ui.dialog.is_none() { @@ -189,12 +182,27 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later Ok(r) } -/// Parenthetical notes after the folder path in a package status (`(2 linked file(s) not found)` …), +/// The status bar's line for a package of `n` files written to `folder` (`None`: the web's +/// download), with `note` from [`package_status_note`] when it isn't empty. With a note and a +/// folder, the note comes before the folder and the folder ends the line. Each catalog also has +/// `@msgplural` rows for the English line, shown after a language switch; the folder takes the rest +/// of the line after `) in `, so a folder name with spaces or parentheses stays whole. +pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String { + let (one, other) = match (folder.is_some(), note.is_empty()) { + (false, true) => ("Packaged {n} file", "Packaged {n} files"), + (false, false) => ("Packaged {n} file {note}", "Packaged {n} files {note}"), + (true, true) => ("Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), + (true, false) => ("Packaged {n} file {note} in {folder}", "Packaged {n} files {note} in {folder}"), + }; + crate::i18n::fmt(&crate::i18n::tn(n, one, other), &[("folder", folder.unwrap_or_default()), ("note", note)]) +} + +/// Parenthetical notes in a package status (`(2 linked files not found)` …), /// joined with spaces and without a leading space (#3494). -fn package_status_note(missing: usize, fonts: &str) -> String { +pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { let mut parts = Vec::new(); if missing > 0 { - parts.push(format!("({})", crate::i18n::fmt(tl!("{count} linked file(s) not found"), &[("count", &missing.to_string())]))); + parts.push(format!("({})", crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found"))); } if !fonts.is_empty() { parts.push(format!("({})", crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))); diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs new file mode 100644 index 0000000000..730c00cb4d --- /dev/null +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -0,0 +1,100 @@ +//! The Symbols panel's Delete Symbol question ([`ask`]). A symbol no instance uses gets "Delete the +//! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand +//! Instances, Delete Instances and Cancel ([`USED`]). +//! +//! Fields: `name` (the symbol) and `doc` (the [`vectorcraft_engine::DocState::uid`] of the document +//! it was asked in). Yes or either Instances button deletes the symbol only while that document is +//! the active one and still has the symbol; an unused symbol that has gained instances since asks +//! the in-use question instead. + +use serde_json::{Value, json}; + +use super::{DialogResult, DialogSpec}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +/// The dialog kind of the question for a symbol no instance uses. +pub const KIND: &str = "deleteSymbol"; + +/// The dialog kind of the question for a symbol with placed instances. +pub const USED: &str = "deleteUsedSymbol"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Delete the selected symbol?").into(), + body: |_, _, _| false, + confirm: confirm_unused, + ok: Some("Yes"), + cancel: Some("No"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +pub(super) const USED_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted.").into(), + body: |_, _, _| false, + confirm: confirm_used, + ok: Some("Expand Instances"), + discard: Some("Delete Instances"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Delete Symbol for symbol `name` of the active document. A symbol with instances always asks +/// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's +/// button) and asked about otherwise. +pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { + let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + match instances(app, uid, name) { + None => {} + Some(0) if now => { + if let Err(e) = app.run("symbol.delete", json!({ "name": name })) { + app.status(e); + } + } + Some(n) => open(app, if n == 0 { KIND } else { USED }, name, uid), + } +} + +fn open(app: &mut VectorcraftApp, kind: &str, name: &str, uid: u64) { + app.ui.dialog = Some(Dialog::new(kind, json!({ "name": name, "doc": uid }))); +} + +/// How many instances symbol `name` has, while the document `uid` is the active one and has the +/// symbol; `None` otherwise. +fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option { + if app.session.active().map(|st| st.uid) != Some(uid) { + return None; + } + let list = app.run("symbol.list", json!({})).ok()?; + list["symbols"].as_array()?.iter().find(|s| s["name"].as_str() == Some(name)).map(|s| s["instances"].as_u64().unwrap_or(0)) +} + +/// The document and symbol `d` asks about. +fn target(d: &Dialog) -> (u64, String) { + (d.fields.get("doc").and_then(Value::as_u64).unwrap_or(0), d.str("name")) +} + +/// Yes: deletes the symbol, or asks the in-use question when it has gained instances. +fn confirm_unused(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + app.ui.dialog = None; + let (uid, name) = target(d); + match instances(app, uid, &name) { + None => Ok(Value::Null), + Some(0) => app.run("symbol.delete", json!({ "name": name })), + Some(_) => { + open(app, USED, &name, uid); + Ok(Value::Null) + } + } +} + +/// Expand Instances (OK) turns the instances into ordinary art; Delete Instances (`discard`) +/// removes them. Either one deletes the symbol in one undo step. +fn confirm_used(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + app.ui.dialog = None; + let (uid, name) = target(d); + if instances(app, uid, &name).is_none() { + return Ok(Value::Null); + } + app.run("symbol.delete", json!({ "name": name, "expandInstances": !d.bool("discard") })) +} diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 47b95b7ea5..80e403d83a 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -118,6 +118,29 @@ fn dialogs_move_by_their_heading_stay_on_screen_and_where_they_were_moved() { } } +/// Tab goes through a dialog's controls and does not stop on the band that moves the window. +#[test] +fn tab_skips_the_band_that_moves_a_dialog() { + let opens: [(&str, Open, egui::Id); 4] = [ + ("Offset Path", |app| crate::menus::invoke(app, "object.path.offsetPath", json!({})), egui::Id::unique(("dialog", "offsetPath"))), + ("New Document", open_new_document, egui::Id::unique(("dialog", "newDocument"))), + ("Preferences", |app| crate::prefs_dialog::open(app, None), egui::Id::unique("dialog-preferences")), + ("Keyboard Shortcuts", crate::shortcut_editor::open, egui::Id::unique("dialog-shortcuts")), + ]; + for (name, open, id) in opens { + let (ctx, mut app) = (ctx(), app_with_selection()); + open(&mut app); + settle(&ctx, &mut app); + let band = modal::handle(id); + assert!(ctx.read_response(band).is_some(), "{name}: the band is drawn"); + let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 30, |events| { + frame(&ctx, &mut app, events); + }); + assert!(!stops.is_empty(), "{name}: Tab reaches the dialog's controls"); + assert!(!stops.contains(&band), "{name}: {stops:?}"); + } +} + /// Open the dialog of a plug-in of `kind` (`effect` or `filter`) with `count` number settings over a /// selection, settle it and `check` it, given its window and heading. The other tests share the /// plug-in registry, and the plug-in is removed after. diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index cd34213afe..816c6641d3 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -167,7 +167,7 @@ fn edits_after_ok_do_not_reach_the_package() { gate.open(); background::wait_all(&mut app); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("package")); - assert!(app.ui.status.starts_with("Packaged 3 file(s) in "), "{}", app.ui.status); + assert!(app.ui.status.starts_with("Packaged 3 files in "), "{}", app.ui.status); let files = files.lock().unwrap(); let (_, bytes) = files.iter().find(|(p, _)| p.ends_with("card.vectorcraft")).unwrap(); assert_eq!(vectorcraft_format::load(bytes).unwrap().node_count(), nodes, "the document as it was at OK"); @@ -213,7 +213,7 @@ fn a_dirty_documents_save_is_written_before_its_package() { release.join().unwrap(); assert_eq!(written(&files), [doc]); assert!(app.background.jobs.is_empty() && !app.session.active().unwrap().is_dirty()); - assert!(app.ui.status.starts_with("Packaged 3 file(s) in "), "the package's status came last: {}", app.ui.status); + assert!(app.ui.status.starts_with("Packaged 3 files in "), "the package's status came last: {}", app.ui.status); } #[test] @@ -254,7 +254,7 @@ fn the_web_downloads_a_zip() { assert!(!frame(&mut app).contains("Location:"), "no folder to choose"); confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); - assert!(app.ui.status.contains("Packaged") && app.ui.status.contains("file(s)"), "{}", app.ui.status); + assert!(app.ui.status.contains("Packaged") && app.ui.status.contains("files"), "{}", app.ui.status); let got = got.borrow(); assert_eq!(got.len(), 1); assert_eq!(got[0].0, "card Folder.zip"); @@ -285,6 +285,71 @@ fn fonts_left_out_of_the_package_are_named() { assert!(app.ui.status.contains(gone), "{}", app.ui.status); } +/// The note on linked files left out of a package uses the form the language's plural rule picks +/// for the count. +#[test] +fn the_missing_links_note_uses_each_count_form() { + let note = |code: &str, missing: usize| { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); + let note = package::package_status_note(missing, ""); + crate::i18n::set_current(crate::i18n::Lang::EN); + note + }; + assert_eq!(note("en", 1), "(1 linked file not found)"); + assert_eq!(note("en", 2), "(2 linked files not found)"); + assert_eq!(note("cs", 1), "(Nenalezen 1 propojený soubor)"); + assert_eq!(note("cs", 2), "(Nenalezeny 2 propojené soubory)"); + assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); +} + +/// A package status written in English, for one file or several, with or without a folder and a +/// note, is translated by every catalog when the status bar shows it after a language switch, in +/// the form the language's plural rule picks for the count, and a folder whose name has a space or +/// parentheses keeps its whole name, next to one note or two. +#[test] +fn an_english_package_status_is_translated_after_a_language_switch() { + use crate::i18n::{Lang, message}; + let folders = [None, Some("/out/card Folder"), Some("/out/card (draft) v2")]; + let notes = ["", "(fonts not copied: Mono)", "(1 linked file not found) (fonts not copied: Mono)"]; + let mut statuses = vec![]; + for n in [1, 3] { + for folder in folders { + for note in notes { + statuses.push((package::package_status(n, folder, note), folder, note)); + } + } + } + let english: Vec<&str> = statuses.iter().map(|(s, ..)| s.as_str()).collect(); + assert!(english.contains(&"Packaged 1 file in /out/card Folder"), "{english:?}"); + assert!(english.contains(&"Packaged 1 file (fonts not copied: Mono) in /out/card (draft) v2"), "{english:?}"); + assert!(english.contains(&"Packaged 3 files"), "{english:?}"); + for lang in Lang::all().filter(|l| l.code() != "en") { + for (s, folder, note) in &statuses { + let shown = message(lang, s); + assert!(!shown.starts_with("Packaged"), "{}: {shown}", lang.code()); + // The folder stays whole in the translated line, and the note's font is still named. + assert!(folder.is_none_or(|f| shown.contains(f)), "{}: {shown}", lang.code()); + assert_eq!(note.contains("Mono"), shown.contains("Mono"), "{}: {shown}", lang.code()); + } + } + let de = Lang::from_code("de").unwrap(); + assert_eq!( + message(de, &package::package_status(1, Some("/out/card (draft)"), "(fonts not copied: Mono)")), + "1 Datei in /out/card (draft) verpackt (fonts not copied: Mono)" + ); + assert_eq!( + message(de, &package::package_status(3, Some("/out/card (draft)"), "(1 linked file not found) (fonts not copied: Mono)")), + "3 Dateien in /out/card (draft) verpackt (1 linked file not found) (fonts not copied: Mono)" + ); + let cs = Lang::from_code("cs").unwrap(); + assert_eq!(message(cs, "Packaged 1 file in /out"), "Zabalen 1 soubor do /out"); + assert_eq!(message(cs, "Packaged 3 files in /out"), "Zabaleny 3 soubory do /out"); + assert_eq!(message(cs, "Packaged 5 files in /out"), "Zabaleno 5 souborů do /out"); + let de = Lang::from_code("de").unwrap(); + assert_eq!(message(de, "Packaged 1 file"), "1 Datei verpackt"); + assert_eq!(message(de, "Packaged 3 files in /out"), "3 Dateien in /out verpackt"); +} + #[test] fn package_status_without_notes_has_no_extra_spaces() { let dir = Folder::new("spaces"); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index af85867d85..dee009b768 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -23,6 +23,8 @@ //! message itself stays English (the control channel, MCP and tests read it); `@msg` catalog //! rows hold whole messages or templates such as `Couldn't open {name}: {e}`, and the values in //! the placeholders are translated in turn (the reason after `: {e}` is often a message too). +//! A `@msgplural` row is a template with a count: its source holds the English `one|other` +//! forms, its translation the language's plural forms, and the `{n}` value picks the form. mod catalog; @@ -651,7 +653,10 @@ pub fn message(lang: Lang, s: &str) -> String { } fn message_at(lang: Lang, s: &str, depth: usize) -> String { - let Some((template, caps)) = lang.catalog().message(s) else { return s.to_string() }; + let Some((forms, caps)) = lang.catalog().message_forms(s) else { return s.to_string() }; + let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); + let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); + let Some(template) = forms.get(form) else { return s.to_string() }; let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, if depth > 1 { message_at(lang, v, depth - 1) } else { v.to_string() })).collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 72c7979c70..4192dabaa8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -203,7 +203,7 @@ font-technology Variable Променливи Apply Paragraph Style Прилагане на стил на абзац Apply SVG Filter… Прилагане на SVG филтър… Apply to All Прилагане към всички - Apply to All ({count} more missing) Прилагане към всички (още {count} липсващи) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Прилагане към всички (още {n} липсващ)|Прилагане към всички (още {n} липсващи) Arc Дъга Arc Lower… Дъга надолу… Arc Tool Инструмент „Дъга“ @@ -735,6 +735,12 @@ font-technology Variable Променливи Delete Stop Изтриване на репер Delete Swatch Изтриване на образец Delete Symbol Изтриване на символ + Delete the selected symbol? Да се изтрие ли избраният символ? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Един или повече от символите се използват и не могат да бъдат изтрити, докато екземплярите им не бъдат разширени или изтрити. + Expand Instances Разширяване на екземплярите + Delete Instances Изтриване на екземплярите + Yes Да + No Не Delete Tab Изтриване на табулация Delete the graphic style “{name}”? Изтриване на графичния стил „{name}“? Delete Theme Изтриване на тема @@ -1581,7 +1587,7 @@ font-technology Variable Променливи Keep the pasted color as a new swatch with a numbered name. Запазване на поставения цвят като нов образец с номерирано име. Keep this row's colors (exclude) Запазване на цветовете на този ред (изключване) Keep: Запазване: - Kerning (0 = Auto) Кернинг (0 = Автоматично) + Kerning Кернинг Keyboard Increment Стъпка с клавиатурата Keyboard Shortcut Conflicts Конфликти на клавишни комбинации Keyboard Shortcut Set Набор клавишни комбинации @@ -2153,6 +2159,7 @@ font-technology Variable Променливи Open the URL in the web browser Отваряне на URL адреса в уеб браузъра Opened with {} note(s): {} Отворено с {} бележка(и): {} Open… Отваряне… + Optical Оптично Optical Margin Alignment Подравняване по оптично поле Optimize for fast web view Оптимизиране за бърз уеб преглед Optimized Оптимизирано @@ -2210,7 +2217,7 @@ font-technology Variable Променливи Package Пакет Package collects a saved document with its linked files and fonts. Пакетът събира запазен документ заедно с неговите свързани файлове и шрифтове. Package created Пакетът е създаден - Packaged {n} file(s) in {folder} {note} Пакетирани са {n} файла в {folder}{note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Пакетиран е {n} файл в {folder} {note}|Пакетирани са {n} файла в {folder} {note} Packaged {n} file(s){note} Пакетирани са {n} файла{note} Package… Пакет… Page Страница @@ -2527,9 +2534,11 @@ font-technology Variable Променливи Stop Спиране Searching… Търсене… Not found Няма намерени резултати - {folders} folder(s) and {files} file(s) searched Претърсени са {folders} папки и {files} файла - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропуснати са {count} папки (като системни папки, папки на други приложения и скрити папки) - {count} folder(s) or file(s) couldn't be read {count} папки или файла не можаха да бъдат прочетени + {folders} and {files} searched Претърсени са {folders} и {files} +@plural {n} folder|{n} folders {n} папка|{n} папки +@plural {n} file|{n} files {n} файл|{n} файла +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Пропусната е {n} папка (като системни папки, папки на други приложения и скрити папки)|Пропуснати са {n} папки (като системни папки, папки на други приложения и скрити папки) +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} папка или файл не можа да бъде прочетен|{n} папки или файла не можаха да бъдат прочетени The search stopped at its limit: search a smaller folder. Търсенето спре поради достигане на лимита: потърсете в по-малка папка. Copy only fonts you own or are licensed to install. Копирайте само шрифтове, които притежавате или имате лиценз да инсталирате. VectorCraft copies the fonts to {folder}. VectorCraft копира шрифтовете в {folder}. @@ -2916,6 +2925,7 @@ font-technology Variable Променливи Shape Mode Режим на фигура Shape Modes: Режими на фигури: Shape Properties: Свойства на фигурата: + Shape Properties Свойства на фигурата Shaper Tool Инструмент „Shaper“ Shapes Фигури Shear Срязване @@ -3597,13 +3607,13 @@ font-technology Variable Променливи Zoom Tool Инструмент „Мащаб“ Zoom with Mouse Wheel Мащабиране с колелцето на мишката Scrub Numeric Fields by Dragging Плъзгане на числени полета чрез влачене - {count} file(s) in {folder} {note}. Show the package folder? {count} файл(а) в {folder}{note}. Показване на папката на пакета? - {count} linked file(s) not found {count} свързан(и) файл(а) не са намерени +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} файл в {folder} {note}. Показване на папката на пакета?|{n} файла в {folder} {note}. Показване на папката на пакета? +@plural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени fonts not copied: {fonts} некопирани шрифтове: {fonts} - {count} linked image(s) changed since this document was saved. Show the new versions? {count} свързано(и) изображение(я) е/са променено(и) след запазването на този документ. Показване на новите версии? - {count} linked image(s) changed on disk. Show the new versions? {count} свързано(и) изображение(я) е/са променено(и) на диска. Показване на новите версии? - {count} more rules: Export writes every one. {count} още правила: Експортът записва всяко едно. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {count} ненаименувани обекта са пропуснати: наименувайте ги или включете „Ненаименувани обекти“ в менюто на панела. +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} свързано изображение е променено след запазването на този документ. Показване на новата версия?|{n} свързани изображения са променени след запазването на този документ. Показване на новите версии? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} свързано изображение е променено на диска. Показване на новата версия?|{n} свързани изображения са променени на диска. Показване на новите версии? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Още {n} правило: Експортът го записва.|Още {n} правила: Експортът записва всяко едно. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} ненаименуван обект е пропуснат: наименувайте го или включете „Ненаименувани обекти“ в менюто на панела.|{n} ненаименувани обекта са пропуснати: наименувайте ги или включете „Ненаименувани обекти“ в менюто на панела. {effect} is already applied {effect} вече е приложен {format} Options Опции за {format} {kind} Gradient {kind} градиент @@ -3625,6 +3635,7 @@ imageTrace Outline Контур @plural {n} item|{n} items {n} обект|{n} обекта @plural Color Table ({n} color)|Color Table ({n} colors) Цветна таблица ({n} цвят)|Цветна таблица ({n} цвята) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Изтриване на този графичен стил ({n})?|Изтриване на тези графични стилове ({n})? +@plural Delete this {n} brush?|Delete these {n} brushes? Изтриване на тази четка ({n})?|Изтриване на тези четки ({n})? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Изтриване на този {n} образец или група?|Изтриване на тези {n} образца и групи? @plural {n} Layer|{n} Layers {n} слой|{n} слоя @plural {n} Object|{n} Objects {n} обект|{n} обекта @@ -3754,6 +3765,7 @@ axis Both И двете Float Tool Group Плаваща група инструменти @msg no library `{id}` няма библиотека `{id}` @msg select some type first първо изберете текст +@msg kerning must be a number, "auto", or "optical" Кернингът трябва да е число, „auto“ или „optical“ @msg {_1} has no {_2} style {_1} няма стил {_2} @msg a layer couldn't be read слой не можа да бъде прочетен @msg it has more than one artboard има повече от една работна област @@ -3822,7 +3834,7 @@ axis Both И двете @msg PDF settings are not an object Настройките за PDF не са обект @msg PDF security settings are not an object Настройките за сигурност на PDF не са обект @msg PDF writer error: {0} Грешка на PDF записа: {0} -@msg Packaged {n} file(s) in {folder} {note} Пакетирани са {n} файла в {folder}{note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Пакетиран е {n} файл в {folder} ({note})|Пакетирани са {n} файла в {folder} ({note}) @msg Packaged {n} file(s){note} Пакетирани са {n} файла{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това) @msg Release Guides: no guides Освобождаване на водачи: няма водачи @@ -5493,13 +5505,13 @@ theme Appearance Външен вид Slope: Наклон: axis X Axis X ос axis Y Axis Y ос -@msg Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} -@msg Packaged {n} file(s) {note} Пакетирани са {n} файла {note} -@msg Packaged {n} file(s) Пакетирани са {n} файла - Packaged {n} file(s) Пакетирани са {n} файла - Packaged {n} file(s) in {folder} Пакетирани са {n} файла в {folder} - Packaged {n} file(s) {note} Пакетирани са {n} файла {note} - {count} file(s) in {folder}. Show the package folder? {count} файл(а) в {folder}. Показване на папката на пакета? +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} +@msgplural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла +@plural Packaged {n} file|Packaged {n} files Пакетиран е {n} файл|Пакетирани са {n} файла +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Пакетиран е {n} файл в {folder}|Пакетирани са {n} файла в {folder} +@plural Packaged {n} file {note}|Packaged {n} files {note} Пакетиран е {n} файл {note}|Пакетирани са {n} файла {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} файл в {folder}. Показване на папката на пакета?|{n} файла в {folder}. Показване на папката на пакета? Clockwise По часовниковата стрелка Dither Дитъринг Fine noise hides banding in the gradient fill Фин шум скрива ивиците в градиентната запълка @@ -5851,6 +5863,11 @@ breakText Glyphs Глифи @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` трябва да е lines, paragraphs, words или glyphs, а не {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` трябва да е "line" или "paragraph", а не {other} @msg `align` must be "left", "center" or "right", not {other} `align` трябва да е "left", "center" или "right", а не {other} + File + Number Файл + номер + File + Data Set Name Файл + име на набора от данни + Data Set Name Име на набора от данни +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` трябва да е `fileNumber`, `fileDataSetName` или `dataSetName` +@msg no free data set file name in destination folder Няма свободно име за файл на набор от данни в целевата папка # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Mode Режим @@ -5892,6 +5909,12 @@ breakText Glyphs Глифи Gap 4 Разстояние 4 Dash 5 Тире 5 Gap 5 Разстояние 5 +@msg You must choose a side pattern. Трябва да изберете страничен шаблон. +@msg invalid pattern tile choice невалиден избор на плочка за шаблон +@msg no pattern named `{choice}` няма шаблон с име `{choice}` + Delete the selected brushes? Да се изтрият избраните четки? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Щрихи използват една или повече от тези четки. Да се премахнат ли четките от тези щрихи и да се изтрият четките? + Remove Strokes Премахване на щрихи # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Инструменти за подреждане Arrange in Grid… Подреждане в мрежа… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 622f0e3cb2..8c7a8846bb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -662,7 +662,7 @@ 1 Layer 1 sloj Libraries Biblioteke Links Veze - {count} linked image(s) changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {count}. Prikazati nove verzije? +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih na disku: {n}. Prikazati nove verzije? Update Changed Links Ažuriraj promijenjene veze @msg Updated {_1} linked file(s) changed on disk Ažurirano povezanih datoteka promijenjenih na disku: {_1} Magic Wand Čarobni štapić @@ -1411,7 +1411,8 @@ lighting Light Svjetlo Fractional Widths Djelimične širine Hide Options Sakrij opcije Horizontal Scale % Vodoravna skala % - Kerning (0 = Auto) Podrezivanje (0 = automatski) + Kerning Podrezivanje + Optical Optičko Leading Prored No Break Bez preloma Proportional Metrics Proporcionalna metrika @@ -1481,8 +1482,8 @@ lighting Light Svjetlo Select objects to see their CSS, or Generate CSS for the whole document. Odaberite objekte da vidite njihov CSS ili Generiši CSS za cijeli dokument. The selected objects have no CSS of their own (see below). Odabrani objekti nemaju vlastiti CSS (vidi ispod). Units: {units} Jedinice: {units} - {count} more rules: Export writes every one. Još pravila: {count}; izvoz zapisuje svako. - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Izostavljeno neimenovanih objekata: {count}; imenujte ih ili uključite Neimenovani objekti u meniju panela. +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Još pravila: {n}; izvoz zapisuje svako.|Još pravila: {n}; izvoz zapisuje svako.|Još pravila: {n}; izvoz zapisuje svako. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela.|Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela.|Izostavljeno neimenovanih objekata: {n}; imenujte ih ili uključite Neimenovani objekti u meniju panela. All Categories Sve kategorije Repeat Objects Ponovi objekte Save… Sačuvaj… @@ -2014,6 +2015,7 @@ lighting Light Svjetlo Polygon Properties: Svojstva mnogougla: Rectangle Properties: Svojstva pravougaonika: Shape Properties: Svojstva oblika: + Shape Properties Svojstva oblika Sides: Stranice: Transform options Opcije transformacije Transform Both Transformiši oboje @@ -2374,19 +2376,21 @@ lighting Light Svjetlo Stop Zaustavi Searching… Pretraga… Not found Nije pronađeno - {folders} folder(s) and {files} file(s) searched Pretraženo foldera: {folders}, datoteka: {files} - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Preskočeno foldera: {count}, npr. foldera drugih aplikacija, sistemskih i skrivenih - {count} folder(s) or file(s) couldn't be read Foldera ili datoteka koje nije moguće pročitati: {count} + {folders} and {files} searched Pretraženo: {folders}, {files} +@plural {n} folder|{n} folders {n} folder|{n} foldera|{n} foldera +@plural {n} file|{n} files {n} datoteka|{n} datoteke|{n} datoteka +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih|Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih|Preskočeno foldera: {n}, npr. foldera drugih aplikacija, sistemskih i skrivenih +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Foldera ili datoteka koje nije moguće pročitati: {n}|Foldera ili datoteka koje nije moguće pročitati: {n}|Foldera ili datoteka koje nije moguće pročitati: {n} The search stopped at its limit: search a smaller folder. Pretraga se zaustavila na svom ograničenju: pretražite manji folder. Copy only fonts you own or are licensed to install. Kopirajte samo fontove koje posjedujete ili imate licencu za instaliranje. VectorCraft copies the fonts to {folder}. VectorCraft kopira fontove u {folder}. - Apply to All ({count} more missing) Primijeni na sve (još {count} nedostaje) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Primijeni na sve (još {n} nedostaje)|Primijeni na sve (još {n} nedostaju)|Primijeni na sve (još {n} nedostaje) Ignore Zanemari Linked File Not Found Povezana datoteka nije pronađena Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Zamijenite je drugom datotekom ili je zanemarite: njene slike i dalje prikazuju pregled sačuvan s dokumentom. Replace… Zamijeni… Update Modified Links Ažuriraj izmijenjene veze - {count} linked image(s) changed since this document was saved. Show the new versions? Povezanih slika promijenjenih otkako je dokument sačuvan: {count}. Prikazati nove verzije? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije?|Povezanih slika promijenjenih otkako je dokument sačuvan: {n}. Prikazati nove verzije? Dialog Dijalog Convert Process to Global Pretvori procesne u globalne Create From: Kreiraj iz: @@ -2425,12 +2429,12 @@ lighting Light Svjetlo Fonts whose licence doesn't allow embedding are not copied. Fontovi čija licenca ne dozvoljava ugrađivanje ne kopiraju se. Package collects a saved document with its linked files and fonts. Paket prikuplja sačuvani dokument s njegovim povezanim datotekama i fontovima. Package created Paket je kreiran - Packaged {n} file(s) in {folder} {note} Upakovano datoteka u {folder}: {n} {note} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note}|Upakovano datoteka u {folder}: {n} {note} Packaged {n} file(s){note} Upakovano datoteka: {n}{note} Relink Linked Files to the Document Ponovo poveži povezane datoteke s dokumentom Save the document first? Prvo sačuvati dokument? - {count} file(s) in {folder} {note}. Show the package folder? Datoteka u {folder}: {count} {note}. Prikazati folder paketa? - {count} linked file(s) not found Povezanih datoteka nije pronađeno: {count} +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa? +@plural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} fonts not copied: {fonts} fontovi nisu kopirani: {fonts} Built-in presets are read-only: New… starts an editable copy. Ugrađeni predlošci su samo za čitanje: Novo… započinje kopiju koja se može uređivati. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na radnoj ploči predstavlja {real} {unit} u sceni. @@ -3046,6 +3050,12 @@ theme Appearance Izgled Current Symbol Trenutni simbol Delete Brush Izbriši četkicu Delete Symbol Izbriši simbol + Delete the selected symbol? Izbrisati odabrani simbol? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Jedan ili više simbola se koriste i ne mogu se izbrisati dok se njihove instance ne prošire ili izbrišu. + Expand Instances Proširi instance + Delete Instances Izbriši instance + Yes Da + No Ne Duplicate Brush Dupliciraj četkicu Duplicate Symbol Dupliciraj simbol Edit Symbol Uredi simbol @@ -4108,6 +4118,7 @@ imageTrace Outline Obris @plural {n} stroke|{n} strokes {n} potez|{n} poteza|{n} poteza @msg no library `{id}` nema biblioteke `{id}` @msg select some type first prvo odaberite tekst +@msg kerning must be a number, "auto", or "optical" Podrezivanje mora biti broj, „auto” ili „optical” @msg the selection has no gradient fill odabir nema ispunu gradijentom @msg the selection has no gradient stroke odabir nema potez gradijentom @msg the selection has no pattern fill odabir nema ispunu uzorkom @@ -4189,7 +4200,7 @@ imageTrace Outline Obris @msg PDF settings are not an object PDF postavke nisu objekat @msg PDF security settings are not an object PDF sigurnosne postavke nisu objekat @msg PDF writer error: {0} greška PDF zapisivača: {0} -@msg Packaged {n} file(s) in {folder} {note} Upakovano datoteka u {folder}: {n} {note} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} Upakovano datoteka u {folder}: {n} ({note}) @msg Packaged {n} file(s){note} Upakovano datoteka: {n}{note} @msg Preview in Browser needs the desktop app (the web downloads files instead) Pregledaj u pregledniku zahtijeva desktop aplikaciju (web umjesto toga preuzima datoteke) @msg Release Guides: no guides Oslobodi vodilice: nema vodilica @@ -4854,6 +4865,8 @@ imageTrace Outline Obris @msg the PCX file is cut short PCX datoteka je skraćena @msg the PCX file's header is damaged zaglavlje PCX datoteke je oštećeno @msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX datoteke s {bits}-bitnim pikselima u {planes} ravni nije moguće pročitati +@msg the JPEG 2000 file can't be read datoteku JPEG 2000 nije moguće pročitati +@msg the JPEG 2000 file has an unsupported color space or JPX content datoteka JPEG 2000 ima nepodržan prostor boja ili JPX sadržaj @msg the PSD image is too large to read ({_1} × {_2} pixels) PSD slika je prevelika za čitanje ({_1} × {_2} piksela) @msg zipped 32-bit PSD image data with prediction can't be read zipovani 32-bitni PSD podaci slike s predviđanjem ne mogu se pročitati @msg {depth}-bit PSD files in this colour mode can't be read {depth}-bitne PSD datoteke u ovom načinu boja ne mogu se pročitati @@ -5512,13 +5525,13 @@ mark-style Japanese Japanski Slope: Nagib: axis X Axis X osa axis Y Axis Y osa -@msg Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} -@msg Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} -@msg Packaged {n} file(s) Upakovano datoteka: {n} - Packaged {n} file(s) Upakovano datoteka: {n} - Packaged {n} file(s) in {folder} Upakovano datoteka u {folder}: {n} - Packaged {n} file(s) {note} Upakovano datoteka: {n} {note} - {count} file(s) in {folder}. Show the package folder? Datoteka u {folder}: {count}. Prikazati folder paketa? +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n} +@msgplural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note} +@msgplural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n} +@plural Packaged {n} file|Packaged {n} files Upakovano datoteka: {n}|Upakovano datoteka: {n}|Upakovano datoteka: {n} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n}|Upakovano datoteka u {folder}: {n} +@plural Packaged {n} file {note}|Packaged {n} files {note} Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note}|Upakovano datoteka: {n} {note} +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? Datoteka u {folder}: {n}. Prikazati folder paketa?|Datoteka u {folder}: {n}. Prikazati folder paketa?|Datoteka u {folder}: {n}. Prikazati folder paketa? Clockwise U smjeru kazaljke na satu Dither Dithering Fine noise hides banding in the gradient fill Fini šum skriva trake u gradijentnoj ispuni @@ -5859,6 +5872,11 @@ swatch Yellow Green Žuto-zelena Position: Položaj: Font Size: Veličina fonta: shape Open Otvoren + File + Number Datoteka + broj + File + Data Set Name Datoteka + naziv skupa podataka + Data Set Name Naziv skupa podataka +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` mora biti `fileNumber`, `fileDataSetName` ili `dataSetName` +@msg no free data set file name in destination folder Nema slobodnog naziva datoteke skupa podataka u odredišnoj mapi # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Retract Handles Uvuci ručke @@ -5925,6 +5943,12 @@ shape Open Otvoren @msg `follow` must be "average", "a" or "b" `follow` mora biti "average", "a" ili "b" @msg the paths have nothing to merge there putanje tu nemaju šta spojiti @msg the path is locked or hidden putanja je zaključana ili skrivena +@msg You must choose a side pattern. Morate odabrati bočni uzorak. +@msg invalid pattern tile choice nevažeći izbor pločice uzorka +@msg no pattern named `{choice}` nema uzorka pod nazivom `{choice}` + Delete the selected brushes? Izbrisati odabrane četkice? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Potezi koriste jednu ili više ovih četkica. Ukloniti četkice s tih poteza i izbrisati četkice? + Remove Strokes Ukloni poteze # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Alati za raspoređivanje Arrange in Grid… Rasporedi u mrežu… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 29d41ac16b..ea34f60571 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -320,7 +320,7 @@ Apply Paragraph Style Aplica l’estil de paràgraf Apply SVG Filter… Aplica el filtre SVG… Apply to All Aplica-ho a tot - Apply to All ({count} more missing) Aplica-ho a tot ({count} més que falten) +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Aplica-ho a tot ({n} més que falta)|Aplica-ho a tot ({n} més que falten) Apply {name} Aplica {name} Approximate path Aproxima el traçat Arabic Àrab @@ -1052,6 +1052,12 @@ Delete Styles Suprimeix els estils Delete Swatch Suprimeix la mostra Delete Symbol Suprimeix el símbol + Delete the selected symbol? Voleu suprimir el símbol seleccionat? + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. Un o més dels símbols estan en ús i no es poden suprimir fins que se n’expandeixin o se’n suprimeixin les instàncies. + Expand Instances Expandeix les instàncies + Delete Instances Suprimeix les instàncies + Yes Sí + No No Delete Tab Suprimeix la tabulació Delete the graphic style “{name}”? Voleu suprimir l’estil gràfic “{name}”? Delete the library “{name}”? Voleu suprimir la biblioteca “{name}”? @@ -2040,8 +2046,8 @@ Keep visible surfaces only when expanding Conserva només les superfícies visibles en expandir Keep: Conserva: Keeps the document editable: VectorCraft reopens the PDF with nothing lost. For files you'll edit again. Manté el document editable: VectorCraft reobre el PDF sense perdre res. Per a fitxers que editaràs de nou. - Kerning (0 = Auto) Kerning (0 = automàtic) Key Color: Color clau: + Kerning Kerning Keyboard Increment Increment de teclat Keyboard Shortcut Conflicts Conflictes de dreceres de teclat Keyboard Shortcut Set Conjunt de dreceres de teclat @@ -2734,6 +2740,7 @@ Opens files in other apps Obre fitxers en altres aplicacions Opens network connections Obre connexions de xarxa Open… Obre… + Optical Òptic Optical Margin Alignment Alineació òptica de marges Optimize for fast web view Optimitza per a la visualització web ràpida Optimized Optimitzat @@ -2805,10 +2812,10 @@ Package Empaqueta Package collects a saved document with its linked files and fonts. L’empaquetatge recull un document desat amb els fitxers enllaçats i els tipus de lletra. Package created Empaquetatge creat - Packaged {n} file(s) S’han empaquetat {n} fitxers - Packaged {n} file(s) in {folder} S’han empaquetat {n} fitxers a {folder} - Packaged {n} file(s) in {folder} {note} S’han empaquetat {n} fitxers a {folder} {note} - Packaged {n} file(s) {note} S’han empaquetat {n} fitxers {note} +@plural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} S’ha empaquetat {n} fitxer a {folder} {note}|S’han empaquetat {n} fitxers a {folder} {note} +@plural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} Packaged {n} file(s){note} S’han empaquetat {n} fitxers{note} Package… Empaqueta… Page Pàgina @@ -3747,6 +3754,7 @@ Shape Mode Mode de forma Shape Modes: Modes de forma: Shape Properties: Propietats de la forma: + Shape Properties Propietats de la forma Shape: Forma: Shaper Shaper Shaper Tool Eina Shaper @@ -4646,19 +4654,21 @@ Zoom to Selection Amplia a la selecció Zoom Tool Eina de zoom Zoom with Mouse Wheel Zoom amb la roda del ratolí - {count} file(s) in {folder} {note}. Show the package folder? {count} fitxer(s) a {folder} {note}. Voleu mostrar la carpeta del paquet? - {count} file(s) in {folder}. Show the package folder? {count} fitxer(s) a {folder}. Voleu mostrar la carpeta del paquet? - {count} folder(s) or file(s) couldn't be read No s’han pogut llegir {count} carpeta(es) o fitxer(s) - {count} folder(s) skipped, such as other apps' and the system's folders and hidden ones S’han omès {count} carpeta(es), com ara les d’altres aplicacions, les del sistema i les ocultes - {count} linked file(s) not found No s’han trobat {count} fitxer(s) enllaçat(s) - {count} linked image(s) changed on disk. Show the new versions? {count} imatge(s) enllaçada(es) han canviat al disc. Voleu mostrar les versions noves? - {count} linked image(s) changed since this document was saved. Show the new versions? {count} imatge(s) enllaçada(es) han canviat des que es va desar aquest document. Voleu mostrar les versions noves? - {count} more rules: Export writes every one. {count} regles més: l’exportació les escriu totes. +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fitxer a {folder} {note}. Voleu mostrar la carpeta del paquet?|{n} fitxers a {folder} {note}. Voleu mostrar la carpeta del paquet? +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {n} fitxer a {folder}. Voleu mostrar la carpeta del paquet?|{n} fitxers a {folder}. Voleu mostrar la carpeta del paquet? +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No s’ha pogut llegir {n} carpeta o fitxer|No s’han pogut llegir {n} carpetes o fitxers +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones S’ha omès {n} carpeta, com ara les d’altres aplicacions, les del sistema i les ocultes|S’han omès {n} carpetes, com ara les d’altres aplicacions, les del sistema i les ocultes +@plural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imatge enllaçada ha canviat al disc. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat al disc. Voleu mostrar les versions noves? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imatge enllaçada ha canviat des que es va desar aquest document. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat des que es va desar aquest document. Voleu mostrar les versions noves? +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla més: l’exportació l’escriu.|{n} regles més: l’exportació les escriu totes. {count} of {total} artboards {count} de {total} taulers - {count} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. S’han omès {count} objectes sense nom: poseu-los un nom o activeu Objectes sense nom al menú del panell. +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. S’ha omès {n} objecte sense nom: poseu-li un nom o activeu Objectes sense nom al menú del panell.|S’han omès {n} objectes sense nom: poseu-los un nom o activeu Objectes sense nom al menú del panell. {effect} is already applied {effect} ja està aplicat {file}, line {line} {file}, línia {line} - {folders} folder(s) and {files} file(s) searched S’han cercat {folders} carpeta(es) i {files} fitxer(s) + {folders} and {files} searched S’han cercat {folders} i {files} +@plural {n} folder|{n} folders {n} carpeta|{n} carpetes +@plural {n} file|{n} files {n} fitxer|{n} fitxers {format} Options Opcions de {format} {kind} Gradient Degradat {kind} {kind} Style Options… Opcions d’estil de {kind}… @@ -4685,6 +4695,7 @@ @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincideix amb {n} drecera per defecte|coincideix amb {n} dreceres per defecte @plural Color Table ({n} color)|Color Table ({n} colors) Taula de colors ({n} color)|Taula de colors ({n} colors) @plural Delete this {n} graphic style?|Delete these {n} graphic styles? Voleu suprimir aquest {n} estil gràfic?|Voleu suprimir aquests {n} estils gràfics? +@plural Delete this {n} brush?|Delete these {n} brushes? Voleu suprimir aquest {n} pinzell?|Voleu suprimir aquests {n} pinzells? @plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? Voleu suprimir aquesta {n} mostra o grup?|Voleu suprimir aquestes {n} mostres i grups? @plural {n} area highlighted|{n} areas highlighted {n} àrea ressaltada|{n} àrees ressaltades @plural {n} color|{n} colors {n} color|{n} colors @@ -5248,10 +5259,10 @@ @msg Opened with {_1} note(s): {_2} Obert amb {_1} nota(es): {_2} @msg Opened {url} Obert {url} @msg Outline Stroke: no stroked paths selected Contorneja el traç: no hi ha cap traçat amb traç seleccionat -@msg Packaged {n} file(s) Empaquetat {n} fitxer(s) -@msg Packaged {n} file(s) in {folder} Empaquetats {n} fitxer(s) a {folder} -@msg Packaged {n} file(s) in {folder} {note} Empaquetats {n} fitxer(s) a {folder} {note} -@msg Packaged {n} file(s) {note} Empaquetats {n} fitxer(s) {note} +@msgplural Packaged {n} file|Packaged {n} files S’ha empaquetat {n} fitxer|S’han empaquetat {n} fitxers +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} S’ha empaquetat {n} fitxer a {folder}|S’han empaquetat {n} fitxers a {folder} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} S’ha empaquetat {n} fitxer a {folder} ({note})|S’han empaquetat {n} fitxers a {folder} ({note}) +@msgplural Packaged {n} file {note}|Packaged {n} files {note} S’ha empaquetat {n} fitxer {note}|S’han empaquetat {n} fitxers {note} @msg Packaged {n} file(s){note} Empaquetats {n} fitxer(s){note} @msg Packaging {_1} Empaquetant {_1} @msg page size {w} × {h} mida de pàgina {w} × {h} @@ -5347,6 +5358,7 @@ @msg select paths or anchor points selecciona traçats o punts d’ancoratge @msg select paths to join selecciona traçats per unir @msg select some type first selecciona text primer +@msg kerning must be a number, "auto", or "optical" El kerning ha de ser un nombre, «auto» o «optical» @msg Select text or click into text with the Type tool to insert glyphs Selecciona text o fes clic dins del text amb l’eina de text per inserir glifs @msg select the art to export first selecciona primer la il·lustració que vols exportar @msg select the art to repeat selecciona la il·lustració que vols repetir @@ -5860,6 +5872,11 @@ anchor Points: Punts: # Color Effects add-on: Vector Halftone (Effect › Color Effects). Dot Color from Art Color dels punts de la il·lustració + Basic Character Formats Formats bàsics de caràcters + Case Majúscules i minúscules +@msg {label} must be a number {label} ha de ser un nombre +@msg {label} must be a number of at least 0.1 {label} ha de ser un nombre de com a mínim 0,1 +@msg no character style `{name}` No s'ha trobat l'estil de caràcter `{name}` # Color Effects add-on: Duotone (Effect › Color Effects) and Print Ink Fixes (Object › Plug-ins › Color Effects). Duotone… Bitò… @@ -5952,6 +5969,11 @@ breakText Glyphs Glifs @msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` ha de ser lines, paragraphs, words o glyphs, no {other} @msg `kind` must be "line" or "paragraph", not {other} `kind` ha de ser "line" o "paragraph", no {other} @msg `align` must be "left", "center" or "right", not {other} `align` ha de ser "left", "center" o "right", no {other} + File + Number Fitxer + número + File + Data Set Name Fitxer + nom del conjunt de dades + Data Set Name Nom del conjunt de dades +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` ha de ser `fileNumber`, `fileDataSetName` o `dataSetName` +@msg no free data set file name in destination folder No hi ha cap nom de fitxer de conjunt de dades lliure a la carpeta de destinació # Path Precision Tools add-on: Path Effects (Effect › Path Effects). Path Effects Efectes de traçat @@ -5992,6 +6014,14 @@ breakText Glyphs Glifs Gap 4 Separació 4 Dash 5 Guió 5 Gap 5 Separació 5 +@msg the JPEG 2000 file can't be read no es pot llegir el fitxer JPEG 2000 +@msg the JPEG 2000 file has an unsupported color space or JPX content el fitxer JPEG 2000 té un espai de color o contingut JPX no compatible +@msg You must choose a side pattern. Heu de triar un patró lateral. +@msg invalid pattern tile choice opció de mosaic de patró no vàlida +@msg no pattern named `{choice}` no hi ha cap patró anomenat `{choice}` + Delete the selected brushes? Voleu suprimir els pinzells seleccionats? + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? Hi ha traços que fan servir un o més d’aquests pinzells. Voleu treure els pinzells d’aquests traços i suprimir els pinzells? + Remove Strokes Elimina els traços # Arrange Tools add-on (Object › Plug-ins › Arrange Tools). Arrange Tools Eines d’organització Arrange in Grid… Organitza en quadrícula… diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index a79ce351a2..1be460212a 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -15,7 +15,8 @@ pub struct Catalog { plurals: HashMap>, /// status and error messages without placeholders (`@msg`): English → translation messages: HashMap, - /// status and error messages with `{name}` placeholders (`@msg`), most specific first + /// status and error messages with `{name}` placeholders (`@msg`, and each English form of a + /// `@msgplural` row), most specific first templates: Vec