diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 54130788e1..f4a307cd5c 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -752,6 +752,18 @@ impl Document { /// [`Document::locked_artboards`] leaving out artboard `index`. pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> { + self.locks_except(index, false) + } + + /// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept + /// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too + /// ([`crate::symbols::KeptBoxes::keeping`]). + pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> { + self.locks_except(usize::MAX, true) + } + + /// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes. + fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> { // Art flush with an edge from outside can overlap it by a rounding error, as in // `art_bounds_on` (#1295). let rects: Vec = @@ -770,7 +782,9 @@ impl Document { if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) { objects(layer, &mut pattern_art); } - LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() } + // Nothing is measured without a locked artboard. + let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() }; + LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() } } /// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none. diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index ab571e50b2..3b415ef1ed 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -451,8 +451,9 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip /// outline, as a click there hits it. pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option { let _walk = ArtWalk::open(); - let symbols = doc.symbol_boxes(); - let locks = doc.locked_artboards(); + // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let locks = doc.locked_artboards_kept(); + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); selected.iter().rev().copied().find(|&id| { let Some(chain) = doc.ancestry(id) else { return false }; let nodes: Vec<&Node> = chain.iter().filter_map(|a| doc.node(*a)).collect(); @@ -520,7 +521,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option Vec { let _walk = ArtWalk::open(); - let symbols = doc.symbol_boxes(); + let symbols = doc.kept_symbol_boxes(); let mut out = Vec::new(); if let Some(scope) = opt.scope && let Some(isolated) = doc.node(scope) @@ -725,7 +727,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); h }; - let locks = doc.locked_artboards(); + let locks = doc.locked_artboards_kept(); let on_locked = |id: NodeId| { editable_only && !locks.is_empty() @@ -733,7 +735,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && doc.node(id).is_some_and(|n| locks.holds(n)) }; let skip = &|id| skip(id) || on_locked(id); - let symbols = doc.symbol_boxes(); + // `locks` copies the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); // Isolation mode: only what is inside the isolated container hits. The art around it is // locked, and clicks pass through it (#833). if editable_only @@ -801,6 +804,12 @@ pub fn set_clip_region(f: ClipRegion) { let _ = CLIP_REGION.set(f); } +/// What the regions of clipping paths with live effects depend on outside the document: the +/// registered [`LiveInputs`] now, and whether a [`ClipRegion`] is registered. +pub(crate) fn clip_region_inputs() -> (u64, bool) { + (live_inputs(), CLIP_REGION.get().is_some()) +} + /// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { @@ -1620,7 +1629,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { let _walk = ArtWalk::open(); let art = InstanceArt::of(doc, inst)?; - let symbols = doc.symbol_boxes(); + let symbols = doc.kept_symbol_boxes(); let mut path = vec![]; let outline = opt.outline || below_preview_off(doc, inst, opt.scope); let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false }; @@ -2042,7 +2051,9 @@ fn previews_off(n: &Node) -> bool { fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let _walk = ArtWalk::open(); let mut out = Vec::new(); - let symbols = doc.symbol_boxes(); + // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let locks = doc.locked_artboards_kept(); + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); // The objects the marquee may touch ([`Top`]). let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the @@ -2284,7 +2295,6 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } } } - let locks = doc.locked_artboards(); for (t, r, outline, edge, drawn) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index cd4798c76c..a616080bce 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -608,6 +608,18 @@ impl Node { } } + /// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no + /// node after it is visited, and the break is returned. + pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow) -> std::ops::ControlFlow { + f(self)?; + if let Some(ch) = self.children() { + for c in ch { + c.try_walk(f)?; + } + } + std::ops::ControlFlow::Continue(()) + } + /// Count of nodes in this subtree, ruler guides left out. pub fn count(&self) -> usize { let mut n = 0; diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index db21762f61..789e0f66b2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -805,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() { assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice)); assert_eq!(calls, 0); } + +/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its +/// children, its later siblings or its ancestors' later siblings. +#[test] +fn try_walk_ends_at_the_break() { + use std::ops::ControlFlow; + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]); + let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]); + let mut all = vec![]; + root.walk(&mut |n| all.push(n.id)); + let mut seen = vec![]; + assert_eq!( + root.try_walk(&mut |n| { + seen.push(n.id); + ControlFlow::<()>::Continue(()) + }), + ControlFlow::Continue(()) + ); + assert_eq!(seen, all, "without a break it visits what walk visits, in the same order"); + seen.clear(); + let flow = root.try_walk(&mut |n| { + seen.push(n.id); + if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) } + }); + assert_eq!(flow, ControlFlow::Break(NodeId(3))); + assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); +} diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index b6090f8993..db8e6f930c 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,32 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +#[test] +fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() { + for kept in [false, true] { + let mut s = Selection::default(); + for i in 1..=4 { + s.add(NodeId(i)); + } + s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)])); + s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)])); + s.key_anchor = Some((NodeId(2), (0, 0))); + s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] }); + s.guides = vec![NodeId(10)]; + s.key_guide = Some(NodeId(10)); + let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] }; + let mut one_by_one = s.clone(); + for id in ids { + one_by_one.remove(id); + } + let mut all = s.clone(); + all.remove_all(ids); + assert_eq!(all, one_by_one); + assert_eq!(all.key_anchor.is_some(), kept); + assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10)))); + } +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 6d2c14a102..9c25427846 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -8,6 +8,7 @@ //! change; [`Document::map_paints`] replaces whole paints of any kind in the same places. use std::collections::{HashMap, HashSet}; +use std::ops::ControlFlow; use std::sync::Arc; use vectorcraft_color::swatch::REGISTRATION; @@ -340,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map, key: /// and gradient stops (with their link), a dynamic symbol instance's own paints /// ([`override_paints`]), then mesh points (unlinked), in paint order. pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { - n.walk(&mut |m| { + let _ = try_node_colors::<()>(n, &mut |c, s| { + f(c, s); + ControlFlow::Continue(()) + }); +} + +/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one. +pub fn node_has_colors(n: &Node) -> bool { + try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break() +} + +/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no +/// paint or node after it is visited. +fn try_node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow) -> ControlFlow { + n.try_walk(&mut |m| { for p in node_paints(m).chain(override_paints(m)) { match p { - Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?, + Paint::Gradient(g) => { + for s in &g.gradient.stops { + f(&s.color, s.swatch.as_deref())?; + } + } _ => {} } } if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| f(&p.color, None)); + for p in &mesh.points { + f(&p.color, None)?; + } } - }); + ControlFlow::Continue(()) + }) } fn item_paint(it: &AppearanceItem) -> &Paint { @@ -821,4 +843,216 @@ mod tests { node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string)))); assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. + fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { + n.walk(&mut |m| { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| f(&p.color, None)); + } + }); + } + + /// Whether [`full_walk`] finds a color in `n`. + fn full_walk_has_colors(n: &Node) -> bool { + let mut found = false; + full_walk(n, &mut |_, _| found = true); + found + } + + /// The colors of `n` by [`full_walk`], in order. + fn full_walk_colors(n: &Node) -> Vec<(Color, Option)> { + let mut out = vec![]; + full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string)))); + out + } + + fn square(id: u64, fill: Paint, stroke: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0)) + } + + fn holder(id: u64, kind: fn(Vec>) -> NodeKind, children: Vec) -> Node { + Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect())) + } + + /// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color. + fn color_cases() -> Vec<(&'static str, Node, bool)> { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let gradient = |stops: usize| { + let mut g = vectorcraft_color::Gradient::default(); + g.stops.truncate(stops); + Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))) + }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap(); + let mut empty_mesh = mesh.clone(); + empty_mesh.points.clear(); + let text = |fill: Paint| { + let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() }; + let mut n = + Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style)))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n + }; + let image = |colorize: Option| { + let im = crate::ImageObject { + key: "k".into(), + width: 2, + height: 2, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n.extras_mut().colorize = colorize.map(Box::new); + n + }; + let overridden = |fill: Option| { + let mut n = square(22, Paint::None, Paint::None); + n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }]; + n + }; + let masked = { + let mut n = square(23, Paint::None, Paint::None); + n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true))); + n + }; + let group = |children| NodeKind::Group { children, clip: false }; + let clip = |children| NodeKind::Group { children, clip: true }; + let compound = |children| NodeKind::Compound { children, rule: Default::default() }; + let blend = |children| NodeKind::Blend { children, spec: Default::default() }; + let blank = |id| square(id, Paint::None, Paint::None); + vec![ + ("no paint", blank(1), false), + ("solid fill", square(2, red.clone(), Paint::None), true), + ("solid stroke", square(3, Paint::None, red.clone()), true), + ("pattern only", square(4, pattern.clone(), pattern.clone()), false), + ("gradient without stops", square(5, gradient(0), Paint::None), false), + ("gradient with stops", square(6, gradient(2), Paint::None), true), + ("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true), + ("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false), + ("text run fill", text(red.clone()), true), + ("text without paint", text(Paint::None), false), + ("image colorize", image(Some(red.clone())), true), + ("image without colorize", image(None), false), + ("image with a pattern colorize", image(Some(pattern.clone())), false), + ("symbol override fill", overridden(Some(red.clone())), true), + ("symbol override without paint", overridden(None), false), + ("color only in the opacity mask", masked, false), + ("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true), + ("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true), + ("group without color", holder(38, group, vec![blank(39), blank(40)]), false), + ("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true), + ("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true), + ("blend", holder(47, blend, vec![blank(48), blank(49)]), false), + ( + "nested groups, color deepest", + holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]), + true, + ), + ] + } + + #[test] + fn has_colors_matches_the_full_walk() { + for (label, n, expected) in color_cases() { + let all = full_walk_colors(&n); + assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}"); + assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}"); + assert_eq!(node_has_colors(&n), expected, "{label}"); + let mut listed = vec![]; + node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string)))); + assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order"); + } + } + + #[test] + fn has_colors_stops_at_the_first_color() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut stops = vectorcraft_color::Gradient::default(); + stops.stops.push(stops.stops[0].clone()); + let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops))); + let mut later = vec![square(2, gradient, red.clone())]; + later.extend((3..100).map(|id| square(id, red.clone(), red.clone()))); + let n = holder(1, |children| NodeKind::Group { children, clip: false }, later); + let (mut colors, mut nodes) = (0, 0); + let flow = try_node_colors(&n, &mut |_, _| { + colors += 1; + ControlFlow::Break(()) + }); + assert!(flow.is_break()); + assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read"); + let flow = n.try_walk(&mut |m| { + nodes += 1; + if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }); + assert!(flow.is_break()); + assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it"); + } + + /// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in + /// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`. + #[test] + #[ignore = "a timing, not a check"] + fn has_colors_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let count = 100_000u64; + let group = |colored: &dyn Fn(u64) -> bool| { + let children = + (0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) }); + holder(0, |children| NodeKind::Group { children, clip: false }, children.collect()) + }; + let cases = [ + ("every path filled", group(&|_| true)), + ("only the last path filled", group(&|i| i == count - 1)), + ("no path filled", group(&|_| false)), + ]; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + // The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms. + let per_call = |f: fn(&Node) -> bool, n: &Node| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(std::hint::black_box(n))); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 30 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + for (label, n) in &cases { + assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}"); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(full_walk_has_colors, n)); + new.push(per_call(node_has_colors, n)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, nw) = (old[3], new[3]); + println!( + "{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs", + o.0, o.1, nw.0, nw.1 + ); + } + } } diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 99a65ae1f7..a1d34e6adb 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> { consulted: RefCell>>, } +/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and +/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and +/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]). +/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's +/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else +/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art +/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`. +struct KeptKey { + symbols: Vec<(String, std::sync::Weak)>, + guides: Option, + inputs: (u64, bool), +} + +impl KeptKey { + /// The key of the document's 9-slice guides. + const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE; + + fn of(doc: &Document, inputs: (u64, bool)) -> Self { + KeptKey { + symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), + guides: doc.unknown.get(Self::GUIDES).cloned(), + inputs, + } + } + + /// Does this describe `doc`'s symbols as they are now, with inputs `inputs`? + fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool { + self.inputs == inputs + && self.symbols.len() == doc.symbols.len() + && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name) + && self.guides.as_ref() == doc.unknown.get(Self::GUIDES) + } + + fn same(&self, other: &KeptKey) -> bool { + self.inputs == other.inputs + && self.symbols.len() == other.symbols.len() + && self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m) + && self.guides == other.guides + } +} + +/// Art boxes, nesting depths and the name index measured by boxes made by +/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols. +struct Kept { + key: KeptKey, + names: Option>, + measured: HashMap>, + depths: HashMap>, +} + +/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread: +/// clicks can alternate between two open documents. +const KEPT_SETS: usize = 2; + +thread_local! { + /// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first. + static KEPT: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the +/// next ones when dropped. +pub(crate) struct KeptBoxes<'a> { + boxes: SymbolBoxes<'a>, + /// What the measurements depend on, under which they are kept. + key: Option, + /// Other boxes of the same document whose measurements are kept with these + /// ([`Self::keeping`]). + also: Option<&'a SymbolBoxes<'a>>, +} + +impl<'a> std::ops::Deref for KeptBoxes<'a> { + type Target = SymbolBoxes<'a>; + + fn deref(&self) -> &SymbolBoxes<'a> { + &self.boxes + } +} + +impl<'a> KeptBoxes<'a> { + /// These boxes, which also keep the art boxes and nesting depths `other` has measured when + /// dropped. `other` measures the same document, as the boxes of + /// [`Document::locked_artboards_kept`] do. + pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self { + self.also = Some(other); + self + } +} + +impl Drop for KeptBoxes<'_> { + /// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive + /// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice + /// guides are left out: measuring them places art within a budget the boxes share + /// ([`SymbolBoxes::sliced_visual`]). + fn drop(&mut self) { + let Some(key) = self.key.take() else { return }; + let b = &self.boxes; + let mut measured = b.measured.take(); + let mut depths = b.depths.take(); + if let Some(other) = self.also { + for (name, a) in other.measured.borrow().iter() { + measured.entry(name.clone()).or_insert(*a); + } + for (name, d) in other.depths.borrow().iter() { + depths.entry(name.clone()).or_insert(*d); + } + } + measured.retain(|_, a| a.is_none_or(|a| !a.sliced)); + let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths }; + // Nothing is kept while the thread ends or the list is in use. + let _ = KEPT.try_with(|k| { + if let Ok(mut k) = k.try_borrow_mut() { + if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) { + let other = k.remove(i); + kept.names = kept.names.or(other.names); + for (name, a) in other.measured { + kept.measured.entry(name).or_insert(a); + } + for (name, d) in other.depths { + kept.depths.entry(name).or_insert(d); + } + } + k.insert(0, kept); + k.truncate(KEPT_SETS); + } + }); + } +} + impl Document { /// [`SymbolBoxes`] for this document's symbols, none measured yet. pub fn symbol_boxes(&self) -> SymbolBoxes<'_> { @@ -131,6 +259,56 @@ impl Document { } } + /// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured + /// by the last such boxes made on this thread for the same symbols, and keep theirs for the next + /// ones when dropped. The measurements are made again when a symbol's name or art, the symbols' + /// 9-slice guides, or the inputs of the live geometry effects of clipping paths have + /// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept. + pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> { + self.kept_boxes(false) + } + + /// [`Self::symbol_boxes`] that start with a copy of the measurements + /// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves. + pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> { + let mut kept = self.kept_boxes(true); + kept.key = None; + std::mem::replace(&mut kept.boxes, self.symbol_boxes()) + } + + /// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them. + fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> { + let mut boxes = self.symbol_boxes(); + let inputs = crate::hit::clip_region_inputs(); + let found = KEPT + .try_with(|k| { + let mut k = k.try_borrow_mut().ok()?; + let i = k.iter().position(|e| e.key.is_of(self, inputs))?; + if copy { + let e = k.get(i)?; + let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs }; + Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() }) + } else { + Some(k.remove(i)) + } + }) + .ok() + .flatten(); + let key = match found { + Some(e) => { + if let Some(names) = e.names { + // The boxes were just made, so no index is set yet. + let _ = boxes.names.set(names); + } + *boxes.measured.get_mut() = e.measured; + *boxes.depths.get_mut() = e.depths; + e.key + } + None => KeptKey::of(self, inputs), + }; + KeptBoxes { boxes, key: Some(key), also: None } + } + /// Each symbol name of this document → the index of the first symbol of that name (the one a /// name finds). pub(crate) fn symbol_names(&self) -> SymbolNames { @@ -148,6 +326,8 @@ impl Document { thread_local! { /// How many symbols [`Document::symbol_names`] has read on this thread. pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; + /// How many art boxes [`SymbolBoxes::art`] has measured on this thread. + static ART_BOXES_MEASURED: Cell = const { Cell::new(0) }; } impl<'a> SymbolBoxes<'a> { @@ -218,6 +398,8 @@ impl<'a> SymbolBoxes<'a> { pub(crate) fn art(&self, name: &str) -> Option { let cached = self.measured.borrow().get(name).copied(); let b = cached.unwrap_or_else(|| { + #[cfg(test)] + ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1)); let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); self.measured.borrow_mut().insert(name.to_string(), b); b @@ -584,10 +766,10 @@ fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { #[cfg(test)] mod tests { use vectorcraft_color::{Color, Paint}; - use vectorcraft_geom::shapes; + use vectorcraft_geom::{Point, shapes}; use super::*; - use crate::{Appearance, Symbol}; + use crate::{Appearance, NodeId, Symbol}; /// A rectangle filled black, with a `stroke` pt black stroke (0: none). fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node { @@ -911,4 +1093,192 @@ mod tests { assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0); assert_eq!(runs.get(), MAX_REACHES + 2); } + + /// How many art boxes `f` measures on this thread. + fn art_boxes_measured(f: impl FnOnce()) -> usize { + let before = ART_BOXES_MEASURED.with(Cell::get); + f(); + ART_BOXES_MEASURED.with(Cell::get) - before + } + + /// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an + /// instance of each at (40 i + 20, 20). + fn ten_symbols() -> Document { + let mut d = Document::new(400.0, 100.0); + let layer = d.layers.first().map(|l| l.id); + for i in 0..10 { + let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0); + symbol(&mut d, &format!("S {i}"), vec![square]); + let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0))); + d.insert(layer, usize::MAX, at).unwrap(); + } + d + } + + #[test] + fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit"); + assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1); + } + assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10); + }; + let first = art_boxes_measured(clicks); + assert_eq!(first, 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_measure_a_symbol_again_after_it_changes() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + // Past the square of "S 1" at (60, 20). + let past = Point::new(71.0, 20.0); + assert!(hit::hit_test(&d, past, HitOptions::default()).is_none()); + // The art grows 3 times in place: no other copy of it is held in the document. + Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false); + let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit")); + assert!(measured > 0); + // New art for "S 2", 40 wide. + let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0); + d.symbols[2].art = Arc::new(wide); + assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit"); + // "S 3" renamed: its instance now shows the 20 × 20 square. + d.symbols[3].name = "Renamed".into(); + assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + } + + /// What clicks on a grid over `d` hit, and what a marquee over it selects. + fn hits(d: &Document) -> (Vec>>, Vec) { + use crate::hit::{self, HitOptions}; + let mut clicks = Vec::new(); + for y in (0..400).step_by(5) { + for x in (0..400).step_by(5) { + let p = Point::new(f64::from(x), f64::from(y)); + clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry)); + } + } + (clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false)) + } + + /// [`hits`] with no measurements kept from earlier hit tests. + fn fresh_hits(d: &Document) -> (Vec>>, Vec) { + KEPT.with_borrow_mut(Vec::clear); + hits(d) + } + + /// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is + /// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without + /// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150. + fn sliced_holder(guides: bool) -> Document { + let mut d = Document::new(400.0, 400.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + if guides { + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + } + let panel = instance(&mut d, "Panel", Affine::IDENTITY); + symbol(&mut d, "Holder", vec![panel]); + let layer = d.layers.first().map(|l| l.id); + let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0)); + d.insert(layer, usize::MAX, holder).unwrap(); + d + } + + #[test] + fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() { + use crate::hit::{self, HitOptions}; + let mut d = sliced_holder(false); + // Left of the frame, where only the bar placed through the guides draws. + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_none()); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + let before = hits(&d); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] })); + let after = hits(&d); + assert_ne!(after, before, "the size moves the guides"); + assert_eq!(after, fresh_hits(&d)); + } + + #[test] + fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() { + use crate::hit::{self, HitOptions}; + let d = sliced_holder(true); + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()); + // The holder's art holds an instance of a symbol with guides; the panel's art holds none. + KEPT.with_borrow(|k| { + let measured = &k[0].measured; + assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys()); + }); + let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some())); + assert!(again > 0, "the holder's art box measured again"); + } + + #[test] + fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() { + let d = ten_symbols(); + let key = KeptKey::of(&d, (0, false)); + assert!(key.is_of(&d, (0, false))); + assert!(!key.is_of(&d, (1, false)), "live inputs changed"); + assert!(!key.is_of(&d, (0, true)), "a clip region registered"); + } + + #[test] + fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard"); + assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty()); + } + }; + assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + // A marquee passes over the objects on a locked artboard without measuring them itself: only + // its locks measure their art. + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty()); + assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_hold_no_symbol_art() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default())); + assert!(KEPT.with_borrow(|k| !k.is_empty())); + assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art"); + } + + #[test] + fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() { + use crate::hit::{self, HitOptions}; + let docs = [ten_symbols(), ten_symbols(), ten_symbols()]; + let p = Point::new(20.0, 20.0); + for d in &docs { + drop(hit::hit_test(d, p, HitOptions::default())); + } + assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS); + // The last two are kept, the first is measured again. + let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default())))); + assert_eq!(kept, 0); + let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default()))); + assert!(first > 0); + } } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 5e95244e26..274f9bdcc4 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -720,7 +720,9 @@ fn moved_type_group(n: &Node) -> Option { /// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live /// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is /// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of -/// them. `None` when no type stays type. +/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster +/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the +/// canvas draws it ([`evaluate_container`]). fn container_keeping_type(d: &Document, n: &Node) -> Option { fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) { if !clipping { @@ -756,7 +758,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { } } } - if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) + || has_pathfinder(n) + || has_own_paint(n) + || crate::reshape::copied_container_raster_at(n).is_some() + { return None; } let fx = geometry_effects(n); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 63215d897d..9531159e01 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -832,11 +832,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl /// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live /// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and /// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -901,6 +905,63 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let mut m = n.clone(); + let mut guides = vec![]; + take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); + let mut source = m.clone(); + source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec(); + // With no geometry effect before the Transform effect, `evaluate_container` leaves the members' + // own effects live (it only paints the group's own fills and strokes): the members are drawn + // first, so their effects apply before the copies are made. + if crate::reshape::geometry_effects(&source).is_empty() { + source = crate::reshape::outlined_members(doc, &source); + // The members' raster effects follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut source); + } + let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { + let mut p = source.clone(); + p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); + p + }); + // The piece is one copy: the transparency, opacity mask and guides stay on the art. + piece.name = None; + piece.visible = true; + piece.locked = false; + (piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false); + piece.extras_mut().mask = None; + // The copies are made about the piece's bounds, measured first: a layer leaves its hidden + // members out of them, and a group does not. + let bounds = piece.geometric_bounds(); + // A layer's copies are groups in it. + if let NodeKind::Layer { children, clip, .. } = &mut piece.kind { + piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip }; + } + let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds); + let copies = art.children().cloned().unwrap_or_default(); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind { + *children = copies; + *clip = false; + } + m.appearance.items.clear(); + m.appearance.contents_index = None; + m.appearance.effects = effects; + if let Some(ch) = m.children_mut() { + ch.extend(guides); + } + m +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 441e78e9e2..50ecc6b549 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -208,6 +208,110 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option { (carried && !excluded).then_some(t) } +/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect +/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of +/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes +/// copies, when a visible raster effect that follows a Transform effect is listed before it and +/// every other visible effect before it is a geometry effect or such a raster effect. `None` +/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a +/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints +/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own. +pub(crate) fn copied_container_raster_at(n: &Node) -> Option { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let effects = &n.appearance.effects; + // Checked first: this runs for every group and layer drawn. + if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return None; + } + let t = effects.iter().rposition(|e| { + e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0 + })?; + let before = effects.get(..t)?; + let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)); + let excluded = n.is_compound_shape() + || n.extras().shaper.is_some() + || crate::has_pathfinder(n) + || n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + || crate::has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) + || effects.iter().any(|e| painted_plugin(e).is_some()) + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); + (carried && !excluded).then_some(t) +} + +/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`, +/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster +/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding +/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved, +/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale +/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect +/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as +/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies +/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have +/// their raster effects moved, turned, reflected and scaled with each copy in the same way +/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art +/// and the raster effects from `t` on, as they ran. +pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option) -> (Node, Vec) { + let rest = n.appearance.effects.get(t..).unwrap_or_default(); + let own = piece.appearance.effects.clone(); + let original = piece.clone(); + let mut art = Node::group(n.id, vec![Arc::new(piece)]); + if let (Some(e), Some(bounds)) = (rest.first(), bounds) { + let params = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); + let max = Budget::EFFECTS.at_least(art_cost(&art)); + copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(¶ms)), max); + if let Some(children) = art.children_mut() { + // The original is last, and each copy above it is mapped once more by `m`. + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let mut a = Affine::IDENTITY; + for (k, c) in children.iter_mut().rev().enumerate() { + // Each copy is the piece in a group of its own: the piece takes its place. + if let Some([one]) = c.children().map(Vec::as_slice) { + *c = one.clone(); + } + if k > 0 { + a *= step; + // Scale Strokes & Effects scaled the copy's own effects with it: they follow + // its map from their values on the original instead. + let copy = Arc::make_mut(c); + copy.appearance.effects = own.clone(); + crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY); + follow_carried(copy, &original, n.id, a); + } + } + } + } + let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); + let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (false, false), doc); + let mut ran = n.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); + (art, effects) +} + +/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a +/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster +/// effects of the matching members of `original`, the piece `copy` was made from, made to follow +/// `a` ([`crate::raster::follow_contents`]). +fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) { + let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return }; + for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) { + let c = Arc::make_mut(c); + c.appearance.effects = w.appearance.effects.clone(); + crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY); + follow_carried(c, w, id, a); + } +} + /// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id, /// else `None`. fn painted_plugin(e: &Effect) -> Option<&str> { @@ -1172,9 +1276,10 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou /// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect /// on for a path, compound path, type, image or symbol instance whose copies each carry the raster -/// effects listed before it ([`copied_raster_at`]). +/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do +/// ([`copied_container_raster_at`]). pub fn outer_effects(n: &Node) -> &[Effect] { - match copied_raster_at(n) { + match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) { Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), None => &n.appearance.effects, } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index e463fb5332..dcb6ef9cfb 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -781,7 +781,7 @@ fn a_groups_transform_moves_its_members_shadows() { } /// A group's Transform effect that makes copies or moves at random leaves its members' shadows as -/// they are, as it leaves the shadows listed before it in its own effects. +/// they are. #[test] fn a_groups_copying_transform_leaves_its_members_shadows() { for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] { @@ -792,6 +792,204 @@ fn a_groups_copying_transform_leaves_its_members_shadows() { } } +/// A layer of `members` with `effects` of its own. +fn layer(id: u64, members: Vec, effects: Vec) -> Node { + let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = members.into_iter().map(std::sync::Arc::new).collect(); + } + l.appearance.effects = effects; + l +} + +/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order. +fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> { + art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect() +} + +fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y)) +} + +/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed +/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and +/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and +/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not +/// scaled a second time. A layer's art stays a layer. +#[test] +fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() { + let cases = [ + (json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]), + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + ]; + for (params, want) in cases { + let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect(); + for container in ["group", "layer"] { + let members = vec![square(101, vec![]), square(102, vec![])]; + let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]; + let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) }; + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}"); + let art = crate::evaluate_container(None, &n).unwrap(); + assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}"); + assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects); + let drawn = copy_shadows(&art); + assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}"); + assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none"); + for c in art.children().into_iter().flatten() { + assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}"); + } + let b = baked(n); + assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b)); + } + } +} + +/// A group's copying Transform effect leaves its members' own shadows on each copy as they are, +/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip +/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has +/// Transform Objects off, leaves the group's shadows on the group. +#[test] +fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() { + let g = group( + 110, + vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)], + ); + assert_eq!(crate::outer_effects(&g).len(), 2); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art)); + + let mut clip = square(121, vec![]); + if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]); + if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(!art.clips()); + assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}"); + assert!(close_all(©_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art)); + + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert_eq!(crate::outer_effects(&g).len(), 2, "{params}"); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow"); + } +} + +/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without +/// one, and no shadow is left without its copy. +#[test] +fn a_groups_copies_past_the_budget_each_keep_their_shadow() { + let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + let paths = paths_in(&art); + assert!(paths > 1 && paths < 1001, "{paths}"); + assert_eq!(shadows_in(&art).len(), paths); +} + +/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow. +#[test] +fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() { + let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None }); + let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let ch = art.children().unwrap(); + assert_eq!(ch.len(), 4, "three copies, then the guide"); + assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1); + assert_eq!(shadows_in(&art).len(), 3); +} + +/// The bounds of every node with `id` under `art`, in order. +fn bounds_of(art: &Node, id: u64) -> Vec { + let mut out = vec![]; + art.walk(&mut |m| { + if m.id == NodeId(id) + && let Some(b) = m.geometric_bounds() + { + out.push(b); + } + }); + out +} + +fn rects_near(a: &[Rect], b: &[Rect]) -> bool { + let near = |p: f64, q: f64| (p - q).abs() < 1e-6; + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1)) +} + +/// A group with a fill of its own and only a shadow before its copying Transform effect applies +/// its members' own effects before it copies them, as a group without a fill does: a member's own +/// move is turned with each copy. +#[test] +fn a_painted_groups_copies_take_their_members_own_effects_first() { + let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])]; + let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))]; + let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap(); + let mut painted = group(170, members(), effects()); + *painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + painted.appearance.effects = effects(); + let art = crate::evaluate_container(None, &painted).unwrap(); + let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171)); + assert!(!want.is_empty()); + assert!(rects_near(&got, &want), "{got:?} {want:?}"); +} + +/// A layer's copies are made about the bounds of its visible members, as the layer measures them: +/// a hidden member does not move the center that a reflected copy turns about. +#[test] +fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() { + let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]); + hidden.visible = false; + let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let got = bounds_of(&art, 181); + assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}"); +} + +/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each +/// copy of a later one, drawn and baked. +#[test] +fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() { + let g = || { + group( + 190, + vec![square(191, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))], + ) + }; + let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)]; + let art = crate::evaluate_container(None, &g()).unwrap(); + assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art)); + let b = baked(g()); + assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b)); +} + +/// A group holding type whose Transform effect only moves its copies, baked for export, gives each +/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type +/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs +/// and the test is skipped. +#[test] +fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { + use vectorcraft_doc::text::{CharStyle, TextObject}; + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); + let b = baked(g); + assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); +} + /// The Transform effects inside a group apply before the group's: a member's own turn of 90° /// applies to its shadow before the group's uneven scale does, for the member's own shadow, its /// fill's shadow, and the shadow of a member of a nested group that has the turn. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f38e23bb5d..5ed472b39a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1189,9 +1189,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } if is_explicit { - for id in &ids { - sel.remove(*id); - } + sel.remove_all(ids.iter().copied()); sel.prune(d); } else { sel.clear(); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cbe942183a..f21adcbc10 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1238,6 +1238,69 @@ fn expand_node_except( } } +/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects +/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]): +/// the copies become groups of their own with those effects, and they and what they hold get ids +/// of their own, so they expand as its members do; the raster effects after the Transform effect +/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect +/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does, +/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of +/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there. +/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when +/// such a copy still holds a random Transform effect after the raster budget left part of it as +/// it is: its new ids would give that effect another seed. +fn copies_carrying_raster( + d: &mut Document, + n: &mut Node, + (brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]), + kept: &mut Vec, + members: &mut std::collections::HashMap>, + (out, listed): (&mut Vec, &mut bool), + raster: &mut RasterBudget, +) -> std::result::Result { + if !carries_copies(n) { + return Ok(false); + } + let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) }; + let mut seen = std::collections::HashSet::from([n.id]); + for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { + let c = Arc::make_mut(c); + let left = raster.left; + let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster)); + if expanded.is_some() && raster.left > left && has_seeded(c) { + return Err(OverBudget); + } + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); + } + fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default()); + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + if let Some(expanded) = expanded { + members.insert(c.id, expanded); + } + } + if !*listed { + out.push((n.id, 0)); + *listed = true; + } + *n = m; + Ok(true) +} + +/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed +/// before it ([`copies_carrying_raster`])? +fn carries_copies(n: &Node) -> bool { + is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len() +} + /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when /// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk /// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded. @@ -1267,10 +1330,13 @@ fn expanded_node( } _ => None, }; - // The embedded images before the adjustment, when the raster budget may yet leave `n` as it - // is: the recolored copies the adjustment adds then go again. - let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) + // The embedded images before the adjustment and the expansions of the copies + // ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the + // recolored copies and the images those add then go again. + let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n)) .then(|| d.images.keys().cloned().collect::>()); + // What the raster budget had left before those expansions: it gets back what they took. + let budget_before = (raster.images, raster.pixels); if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1316,23 +1382,30 @@ fn expanded_node( } return Some(m); } + // New ids of the copies of objects `skip` lists among the members. + let mut kept = vec![]; + // Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id, + // with what their expansion lists. + let mut members = std::collections::HashMap::new(); + let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster); // Raster effects whose image would go past the budget stay: so does the object, with what is - // inside it and its color adjustments (a symbol instance stays an instance of its symbol). - let Ok(image) = raster_image(d, &n, raster) else { + // inside it and its color adjustments (a symbol instance stays an instance of its symbol), and + // so does a group or layer whose copies keep a random Transform effect the budget left. + let Ok(image) = copies.and_then(|copied| { + changed |= copied; + raster_image(d, &n, raster) + }) else { out.truncate(listed_before); if let Some(keys) = images_before { d.images.retain(|k, _| keys.contains(k)); } + (raster.images, raster.pixels) = budget_before; return None; }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); - // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. - let mut members = std::collections::HashMap::new(); - // New ids of the copies of objects `skip` lists among those members. - let mut kept = vec![]; let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -1344,7 +1417,7 @@ fn expanded_node( } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster); + members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 5a1146f28f..d035c24860 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1150,3 +1150,42 @@ fn an_image_past_the_pixels_left_stays_unmade() { let mut budget = super::RasterBudget { images: 0, pixels, left: 0 }; assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left"); } + +/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a +/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it +/// is when the raster budget has no image left for a copy's shadow, with none left or with one for +/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as +/// before, and the document holds no image the first copy's expansion made, nor the budget its +/// charge. +#[test] +fn copies_the_raster_budget_leaves_keep_their_random_moves() { + let (mut s, id) = session_with_rect(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap()); + let random = json!({"moveH": 40, "moveV": 40, "random": true}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap(); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap(); + let draw = |d: &vectorcraft_doc::Document| { + vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + for images in [0, 1] { + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let before = d.node(g).cloned().unwrap(); + assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow"); + let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::>()); + + let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 }; + let mut out = vec![]; + super::expand_node(&mut d, g, &[], &mut out, &mut budget); + assert!(budget.left > 0, "{images}: a copy's shadow is left"); + assert!(out.is_empty(), "{images}: nothing expands: {out:?}"); + assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is"); + assert!(draw(&d) == drawn, "{images}: the group draws as before"); + assert_eq!(d.images.keys().cloned().collect::>(), keys, "{images}: no image is added"); + assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took"); + } +} diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index e26d9a765a..ff0e14c40d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -286,16 +286,24 @@ fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option< /// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's /// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility -/// is read, its first note saying why: `None` when pages are picked, layers or the editing data -/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks. -fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec)> { +/// is read, its first note saying why. Else `e`: as it is when pages are picked, layers or the +/// editing data are off, or the file has no editing data, and followed by why when the file has +/// editing data that can't be read. Its type is outlines when `opts` asks. +fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<(Document, Vec)> { if opts.pages.is_some() || !opts.layers || !opts.editing_data { - return None; + return Err(e); + } + let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref()) + .and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose()); + match read { + Ok(Some((doc, warnings))) => { + let notes = + std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect(); + Ok(outlined_if_asked(doc, notes, opts)) + } + Ok(None) => Err(e), + Err(why) => Err(err(format!("{e}; its editing data couldn't be read either ({why})"))), } - let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?; - let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?; - let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect(); - Some(outlined_if_asked(doc, notes, opts)) } /// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the @@ -497,7 +505,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result .inspect(|_| editing_data = true), // A PDF part that can't be read (a stream the import refuses): the editing copy // alone where it reads, else the error. - Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), + Err(e) => without_pdf_part(bytes, opts, e).inspect(|_| editing_data = true), } })?; // The File Info of a file read from its pages or its editing copy. diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index d89dab774f..9d263c8c97 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -799,7 +799,7 @@ fn unread_pdf_part(e: &str) -> String { /// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from /// its editing data, with a first note saying why. Pages picked, layers off or the editing data -/// off keep the error, and so does editing data that can't be read. +/// off keep the error. Editing data that can't be read keeps it too, followed by why. #[test] fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() { let mut s = Session::new(); @@ -817,10 +817,25 @@ fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() { } for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) { let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string(); - assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}"); + let both = format!("{plain}; its editing data couldn't be read either (its zlib compression is damaged)"); + assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), both, "{name}"); + for p in [json!({"pages": "1"}), json!({"layers": false})] { + assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), plain, "{name}: {p}"); + } } } +/// #4366: editing data stored in a form the reader doesn't take, beside a PDF part that can't be +/// read, is named in the error. +#[test] +fn the_error_says_why_the_editing_data_couldnt_be_read() { + let mut s = Session::new(); + let file = ai::ai_with_private_streams(&compressed(&ai::sample_data()), ai::page_pdf(), REFUSED_CONTENT, "/Filter /Bogus "); + let plain = open(&mut s, "art.ai", &file, json!({"editingData": false})).unwrap_err().to_string(); + let e = open(&mut s, "art.ai", &file, json!({})).unwrap_err().to_string(); + assert_eq!(e, format!("{plain}; its editing data couldn't be read either (it is stored in a form that isn't read)")); +} + /// A file saved in units of 10 points (`/UserUnit 10`, as in /// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens /// from its editing data at its size in points. diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 791aa47f39..e91fe0ebf1 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -4,7 +4,7 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_doc::{AnchorRef, Document, LockedArtboards, Node, NodeId, NodeKind, Selection}; use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; @@ -930,52 +930,145 @@ fn anchors_many(s: &mut Session, p: &Value) -> Result { None if bool_or(p, "add", false) => "add", None => "set", }; - s.select(|d, sel| { - if mode == "set" { - sel.clear(); - } - for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); - let all: BTreeSet<(usize, usize)> = - d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); - // Anything but a path is selected, toggled or deselected as a whole. - if all.is_empty() { - match mode { - "toggle" => sel.toggle(id), - "subtract" => sel.remove(id), - _ => sel.add(id), - } - continue; - } - // From the anchors selected now (all of them for a path selected as a whole). - let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), - None if sel.contains(id) => all.clone(), - None => BTreeSet::new(), - }; - let refs: BTreeSet<(usize, usize)> = refs.intersection(&all).copied().collect(); - let next: BTreeSet<(usize, usize)> = match mode { - "toggle" => now.symmetric_difference(&refs).copied().collect(), - "subtract" => now.difference(&refs).copied().collect(), - _ => now.union(&refs).copied().collect(), - }; - if next.is_empty() { - sel.remove(id); - continue; - } - sel.add(id); - if next.len() < all.len() { - sel.anchors.insert(id, next); - } else { - sel.anchors.remove(&id); - } - } - })?; + s.select(|d, sel| select_anchor_items(d, sel, items, mode))?; ok() } +/// `select.anchorsMany`'s change to `sel`: each item in order, with the selected objects kept in a +/// [`Members`] map while the items run, so that an item's membership check and change don't go +/// through `sel.objects`. +fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BTreeSet)>, mode: &str) { + if mode == "set" { + sel.clear(); + } + if items.is_empty() { + return; + } + let mut members = Members::of(sel); + for (id, refs) in items { + // A segment pick's endpoints aren't selected anchors: start from none of them. + let segment_pick = sel.segments.remove(&id).is_some(); + let all: BTreeSet = + d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); + // Anything but a path is selected, toggled or deselected as a whole. + if all.is_empty() { + match mode { + "toggle" => members.toggle(sel, id), + "subtract" => members.remove(sel, id), + _ => members.add(sel, id), + } + continue; + } + // From the anchors selected now (all of them for a path selected as a whole). + let now = match sel.partial(id) { + _ if segment_pick => BTreeSet::new(), + Some(a) => a.clone(), + None if members.contains(id) => all.clone(), + None => BTreeSet::new(), + }; + let refs: BTreeSet = refs.intersection(&all).copied().collect(); + let next: BTreeSet = match mode { + "toggle" => now.symmetric_difference(&refs).copied().collect(), + "subtract" => now.difference(&refs).copied().collect(), + _ => now.union(&refs).copied().collect(), + }; + if next.is_empty() { + members.remove(sel, id); + continue; + } + members.add(sel, id); + if next.len() < all.len() { + sel.anchors.insert(id, next); + } else { + sel.anchors.remove(&id); + } + } + members.finish(sel); +} + +/// The selected objects of a [`Selection`] while [`select_anchor_items`] changes them. Each +/// selected id maps to the activation that selected it: 0 for the objects selected before, and +/// a new number for each later [`Members::add`] of an unselected id, which `added` lists in order. +/// [`Members::finish`] writes them back to `objects`. +struct Members { + live: std::collections::HashMap, + added: Vec<(NodeId, usize)>, + removed: bool, +} + +impl Members { + fn of(sel: &Selection) -> Self { + count_objects_walk(); + Self { live: sel.objects.iter().map(|id| (*id, 0)).collect(), added: Vec::new(), removed: false } + } + + fn contains(&self, id: NodeId) -> bool { + self.live.contains_key(&id) + } + + /// [`Selection::add`]: clears what any selection change clears, and selects `id` at the end + /// unless it is selected. + fn add(&mut self, sel: &mut Selection, id: NodeId) { + sel.target = None; + sel.slices.clear(); + sel.symbol_part = None; + sel.on_path_member = None; + if let std::collections::hash_map::Entry::Vacant(e) = self.live.entry(id) { + let activation = self.added.len() + 1; + e.insert(activation); + self.added.push((id, activation)); + } + } + + /// [`Selection::remove`]: clears what any selection change clears, and deselects `id` with + /// its anchors, segments, and the key or key anchor it is. + fn remove(&mut self, sel: &mut Selection, id: NodeId) { + sel.target = None; + sel.slices.clear(); + sel.symbol_part = None; + sel.on_path_member = None; + if self.live.remove(&id).is_some() { + self.removed = true; + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + if sel.key == Some(id) { + sel.key = None; + } + if sel.key_anchor.is_some_and(|(k, _)| k == id) { + sel.key_anchor = None; + } + } + + /// [`Selection::toggle`]. + fn toggle(&mut self, sel: &mut Selection, id: NodeId) { + if self.contains(id) { self.remove(sel, id) } else { self.add(sel, id) } + } + + /// Writes the selected objects to `sel.objects`: the slots of the objects selected before and + /// still selected by that activation, in their order, then the ids selected since and still + /// selected by the activation that added them, in the order they were added. + fn finish(self, sel: &mut Selection) { + if self.removed { + count_objects_walk(); + sel.objects.retain(|id| self.live.get(id) == Some(&0)); + } + sel.objects.extend(self.added.into_iter().filter(|(id, n)| self.live.get(id) == Some(n)).map(|(id, _)| id)); + } +} + +#[cfg(test)] +thread_local! { + /// Tests: how many walks [`select_anchor_items`] made over the selected objects on this thread. + pub(crate) static OBJECTS_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Tests: count one walk over the selected objects. +fn count_objects_walk() { + #[cfg(test)] + OBJECTS_WALKS.set(OBJECTS_WALKS.get() + 1); +} + /// Select › Same › Fill/Stroke Color: is `a` the same colour as `b`? Tints of one global or spot /// swatch are, unless `tint` (General › Select Same Tint %) asks for the same tint too. pub(crate) fn same_paint(a: &Paint, b: &Paint, tint: bool) -> bool { @@ -1287,3 +1380,6 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result { s.select(|_, sel| sel.set(ids))?; Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/select/tests.rs b/crates/engine/src/cmd/select/tests.rs new file mode 100644 index 0000000000..74416ea09e --- /dev/null +++ b/crates/engine/src/cmd/select/tests.rs @@ -0,0 +1,286 @@ +//! `select.anchorsMany`'s item loop ([`select_anchor_items`]) against a loop that changes the +//! selection one item at a time through [`Selection::add`], [`Selection::remove`] and +//! [`Selection::toggle`]. + +use std::collections::{BTreeSet, HashSet}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use vectorcraft_color::Color; +use vectorcraft_doc::{AnchorRef, Document, NodeId, Selection, SymbolPart}; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +use super::{OBJECTS_WALKS, select_anchor_items}; + +type Items = Vec<(NodeId, BTreeSet)>; + +const MODES: [&str; 4] = ["set", "add", "toggle", "subtract"]; + +/// The item loop through `Selection`'s own methods, each of which goes through `objects`. +fn item_by_item(d: &Document, sel: &mut Selection, items: Items, mode: &str) { + if mode == "set" { + sel.clear(); + } + for (id, refs) in items { + let segment_pick = sel.segments.remove(&id).is_some(); + let all: BTreeSet = + d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); + if all.is_empty() { + match mode { + "toggle" => sel.toggle(id), + "subtract" => sel.remove(id), + _ => sel.add(id), + } + continue; + } + let now = match sel.partial(id) { + _ if segment_pick => BTreeSet::new(), + Some(a) => a.clone(), + None if sel.contains(id) => all.clone(), + None => BTreeSet::new(), + }; + let refs: BTreeSet = refs.intersection(&all).copied().collect(); + let next: BTreeSet = match mode { + "toggle" => now.symmetric_difference(&refs).copied().collect(), + "subtract" => now.difference(&refs).copied().collect(), + _ => now.union(&refs).copied().collect(), + }; + if next.is_empty() { + sel.remove(id); + continue; + } + sel.add(id); + if next.len() < all.len() { + sel.anchors.insert(id, next); + } else { + sel.anchors.remove(&id); + } + } +} + +/// A document with `n` four-anchor rectangles and, after them, a group of two more → the +/// rectangles' ids and the group's. +fn doc(n: usize) -> (Document, Vec, NodeId) { + let mut b = DocBuilder::new(2000.0, 2000.0); + let rects = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0); + b.rect(Rect::new(x, y, x + 5.0, y + 5.0), Color::rgb(0.2, 0.4, 0.6), |_| {}) + }) + .collect(); + let black = Color::rgb(0.0, 0.0, 0.0); + let kids = vec![b.rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), black), b.rect_node(Rect::new(2.0, 0.0, 3.0, 1.0), black)]; + let group = b.group(kids, false); + (b.build(), rects, group) +} + +fn anchors(refs: &[(usize, usize)]) -> BTreeSet { + refs.iter().copied().collect() +} + +/// A selection with every field set: rectangles 0 to 4 and the group, rectangle 2 listed twice, +/// partial anchors on 1 and 3, a segment pick on 4, rectangle 1 the key, a key anchor on 3, and a +/// target, slices, guides, a key guide, new art, a symbol part and an on-path member. +fn seeded(r: &[NodeId], group: NodeId) -> Selection { + let mut s = Selection { objects: vec![r[0], r[1], r[2], r[3], group, r[2], r[4]], ..Selection::default() }; + s.anchors.insert(r[1], anchors(&[(0, 0), (0, 1)])); + s.anchors.insert(r[3], anchors(&[(0, 2)])); + s.anchors.insert(r[4], anchors(&[(0, 0), (0, 1)])); + s.segments.insert(r[4], anchors(&[(0, 0)])); + s.key = Some(r[1]); + s.key_anchor = Some((r[3], (0, 2))); + s.target = Some(r[0]); + s.slices = vec![r[5]]; + s.guides = vec![r[6]]; + s.key_guide = Some(r[6]); + s.new_art = Arc::new(HashSet::from([r[2]])); + s.symbol_part = Some(SymbolPart { instance: r[0], path: vec![0] }); + s.on_path_member = Some(r[7]); + s +} + +/// Item lists with repeated ids, removals followed by additions, the group, anchors outside a +/// path, items that empty a path, and the empty list, then pseudo-random lists. +fn item_streams(r: &[NodeId], group: NodeId) -> Vec { + let all = [(0, 0), (0, 1), (0, 2), (0, 3)]; + let mut streams: Vec = vec![ + vec![], + vec![(r[2], anchors(&[(0, 0)]))], + vec![(r[2], anchors(&all)), (r[2], anchors(&all))], + vec![(r[2], anchors(&all)), (r[5], anchors(&[(0, 1)])), (r[2], anchors(&[(0, 3)]))], + vec![(group, anchors(&[])), (group, anchors(&[(0, 0)])), (group, anchors(&[]))], + vec![(r[6], anchors(&[(0, 0)])), (r[6], anchors(&[(0, 0)])), (r[7], anchors(&[(0, 9), (3, 0)]))], + vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&all)), (r[3], anchors(&all))], + vec![(r[4], anchors(&[])), (r[4], anchors(&[(0, 2)]))], + vec![(r[1], anchors(&all)), (r[3], anchors(&all)), (r[1], anchors(&[(0, 0)])), (r[3], anchors(&[(0, 2)]))], + vec![(r[8], anchors(&[(0, 0)])), (r[0], anchors(&all)), (r[8], anchors(&all)), (r[0], anchors(&[(0, 1)]))], + ]; + let pool: Vec = r.iter().copied().chain([group]).collect(); + let mut x: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + for len in [3, 9, 25, 80, 200] { + let items = (0..len) + .map(|_| { + let id = pool[(next() % pool.len() as u64) as usize]; + // Bits 0 to 4 of a draw pick anchors 0 to 3 and one past the end. + let bits = next(); + let refs = (0..5).filter(|i| (bits >> i) & 1 == 1).map(|i| (0, i)).collect(); + (id, refs) + }) + .collect(); + streams.push(items); + } + streams +} + +/// Starting selections: the seeded one, none, every rectangle whole, and every rectangle with +/// one anchor. +fn starts(r: &[NodeId], group: NodeId) -> Vec { + let mut whole = Selection::default(); + whole.set(r.iter().copied().chain([group])); + let mut partial = whole.clone(); + for id in r { + partial.anchors.insert(*id, anchors(&[(0, 1)])); + } + vec![seeded(r, group), Selection::default(), whole, partial] +} + +#[test] +fn anchor_items_do_what_the_item_by_item_loop_does() { + let (d, r, group) = doc(12); + for start in starts(&r, group) { + for items in item_streams(&r, group) { + for mode in MODES { + let mut expected = start.clone(); + item_by_item(&d, &mut expected, items.clone(), mode); + let mut got = start.clone(); + select_anchor_items(&d, &mut got, items.clone(), mode); + assert_eq!(got, expected, "mode {mode}, items {items:?}, from {start:?}"); + assert_eq!(got.new_art, expected.new_art); + } + } + } +} + +#[test] +fn a_path_deselected_and_selected_again_goes_last_without_its_key() { + let (d, r, group) = doc(12); + let all = anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]); + let mut s = seeded(&r, group); + // Toggling the selected anchors of 1 and 3 deselects them; toggling again selects them again. + let items = vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&[(0, 0)])), (r[3], all)]; + select_anchor_items(&d, &mut s, items, "toggle"); + assert_eq!(s.objects, [r[0], r[2], group, r[2], r[4], r[1], r[3]]); + assert_eq!(s.anchors.get(&r[1]), Some(&anchors(&[(0, 0)]))); + assert_eq!(s.anchors.get(&r[3]), None); + assert_eq!((s.key, s.key_anchor), (None, None)); +} + +/// Every rectangle with one anchor, as a Direct Selection marquee sends them. +fn marquee(r: &[NodeId]) -> Items { + r.iter().map(|id| (*id, anchors(&[(0, 0)]))).collect() +} + +/// Every rectangle with all four anchors, which deselects each in subtract mode. +fn every_anchor(r: &[NodeId]) -> Items { + r.iter().map(|id| (*id, anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]))).collect() +} + +#[test] +fn anchor_items_walk_the_selected_objects_at_most_twice() { + let (d, r, group) = doc(2000); + let mut all = Selection::default(); + all.set(r.iter().copied().chain([group])); + for (start, items, mode) in [ + (Selection::default(), marquee(&r), "set"), + (all.clone(), marquee(&r), "toggle"), + (all.clone(), every_anchor(&r), "subtract"), + (all.clone(), every_anchor(&r).into_iter().chain(marquee(&r)).collect(), "toggle"), + ] { + let mut s = start; + OBJECTS_WALKS.set(0); + select_anchor_items(&d, &mut s, items, mode); + let walks = OBJECTS_WALKS.get(); + assert!(walks <= 2, "{mode}: {walks} walks over the selected objects"); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = Instant::now(); + f(); + start.elapsed() + } + } +} + +fn ms(d: Duration) -> f64 { + d.as_secs_f64() * 1000.0 +} + +/// Timings of the item loop and the item-by-item loop on 2,000, 20,000 and 50,000 rectangles, run +/// in turn on clones of the same selection, 7 runs each. Ignored by default; it prints the median, +/// fastest and slowest run and sets no bound on them: +/// `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn anchor_items_perf() { + const RUNS: usize = 7; + eprintln!("anchor_items_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("anchor_items_perf: {:>6} {:<26} {:>28} {:>28}", "paths", "case", "item by item ms (min-max)", "item loop ms (min-max)"); + for n in [2_000, 20_000, 50_000] { + let (d, r, group) = doc(n); + let mut all = Selection::default(); + all.set(r.iter().copied().chain([group])); + for (case, start, items, mode) in [ + ("set, marquee", Selection::default(), marquee(&r), "set"), + ("add, marquee", Selection::default(), marquee(&r), "add"), + ("toggle, Select All", all.clone(), marquee(&r), "toggle"), + ("subtract every anchor", all.clone(), every_anchor(&r), "subtract"), + ] { + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..RUNS { + let (mut a, mut b) = (start.clone(), start.clone()); + let (ia, ib) = (items.clone(), items.clone()); + // The two loops take turns going first. + if run % 2 == 0 { + old.push(time(|| item_by_item(&d, &mut a, ia, mode))); + new.push(time(|| select_anchor_items(&d, &mut b, ib, mode))); + } else { + new.push(time(|| select_anchor_items(&d, &mut b, ib, mode))); + old.push(time(|| item_by_item(&d, &mut a, ia, mode))); + } + assert_eq!(a, b, "{n} paths, {case}"); + } + old.sort(); + new.sort(); + eprintln!( + "anchor_items_perf: {n:>6} {case:<26} {:>10.3} ({:>7.3}-{:>8.3}) {:>10.3} ({:>7.3}-{:>8.3})", + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } + } +} diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 5780e65ed8..33c9ec67bb 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -53,7 +53,15 @@ pub fn specs() -> Vec { has_doc, style_delete ), - cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name} → {name}", has_doc, style_duplicate), + cmd!( + "graphicStyle.duplicate", + "Duplicate Graphic Style", + ["Window", "Graphic Styles"], + None, + "{name} a copy of the style at the end of the list, named ` copy` (` copy 2`… when that is taken); no object is linked to it → {name}", + has_doc, + style_duplicate + ), cmd!( query "graphicStyle.list", "List Graphic Styles", @@ -431,7 +439,7 @@ fn style_duplicate(s: &mut Session, p: &Value) -> Result { let pos = style_index(d, &name)?; let nm = unique_name(&format!("{name} copy"), |n| d.graphic_style(n).is_some()); let g = GraphicStyle { name: nm.clone(), id: d.next_graphic_style_id(), ..d.graphic_styles[pos].clone() }; - d.graphic_styles.insert(pos + 1, g); + d.graphic_styles.push(g); Ok(nm) })?; Ok(json!({"name": new})) diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 05da523ced..52cf1381cd 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -302,6 +302,136 @@ fn each_copys_fill_shadow_expands_as_the_canvas_draws_it() { } } +/// Each copy of a group's Transform effect draws the drop shadow listed before the effect under +/// itself, of both its squares together and scaled with it, and Expand Appearance keeps those +/// shadows: the squares (20..40 together) have their shadow 20 pt to their right, and their copy +/// scaled 200 % and moved 80 pt down (10..50 across, 90..130 down) has its own 40 pt to its right. +/// A copy moved 30 pt right (50..70) lies under the squares' shadow (40..60), which still paints +/// over it once expanded. The expanded art has no effects left, and each object in it an id of its +/// own. +#[test] +fn each_copys_shadow_on_a_group_expands_as_the_canvas_draws_it() { + let cases = [ + (json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}), (80, 110), "the copy's shadow"), + (json!({"moveH": 30, "copies": 1}), (55, 30), "the squares' shadow over the copy"), + ]; + for (params, (x, y), what) in cases { + let mut s = session(); + let mut ids = vec![]; + for x in [20, 30] { + ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 20}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + } + run(&mut s, "select.set", json!({"ids": ids})); + run(&mut s, "object.group", json!({})); + let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": params})); + let before = render(&s); + assert_eq!(before.pixel(x, y), [0, 255, 0, 255], "{params}: {what}"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{params}: {diff} pixels differ"); + let doc = &s.doc().unwrap().doc; + let (mut seen, mut count, mut effects) = (std::collections::HashSet::new(), 0, 0); + for l in &doc.layers { + l.walk(&mut |n| { + seen.insert(n.id); + count += 1; + effects += n.appearance.effects.len(); + }); + } + assert_eq!(seen.len(), count, "{params}: each object has an id of its own"); + assert_eq!(effects, 0, "{params}: no effects are left"); + } +} + +/// A member's random Transform effect takes its seed from the member's id, and the canvas draws +/// every copy of the group with that id: Expand Appearance of a group with a stroke of its own, a +/// shadow and a copying Transform effect gives each copy's symbol instance the same random move, so +/// the copies, 60 pt apart, still draw alike. +#[test] +fn each_copys_random_member_expands_as_the_canvas_draws_it() { + let mut s = session(); + let mut ids = vec![]; + for x in [20, 50] { + ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + } + run(&mut s, "select.set", json!({"ids": [ids[0]]})); + ids[0] = run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [ids[0]]})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveH": 16, "moveV": 16, "random": true}})); + run(&mut s, "select.set", json!({"ids": ids})); + let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [g]})); + run(&mut s, "appearance.addStroke", json!({})); + assert!(node(&s, NodeId(g)).appearance.items.iter().any(|i| i.visible()), "the group has a stroke of its own"); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveV": 60, "copies": 2}})); + // The pixels of each copy's 60 pt band that differ from the first copy's by more than 64. + let unlike = |r: &vectorcraft_render::Rendered| { + let px = |x: usize, y: usize| { + let i = (y * r.width as usize + x) * 4; + r.pixels.get(i..i + 4).map(<[u8]>::to_vec).unwrap_or_default() + }; + let mut n = 0; + for k in [60, 120] { + for y in 0..60 { + for x in 0..r.width as usize { + n += usize::from(px(x, y).iter().zip(px(x, y + k)).any(|(a, b)| a.abs_diff(b) > 64)); + } + } + } + n + }; + let before = render(&s); + assert_eq!(unlike(&before), 0, "the canvas draws the copies alike"); + let art = vectorcraft_render::effects::evaluate_container(Some(&s.doc().unwrap().doc), &node(&s, NodeId(g))).unwrap(); + let mut live = 0; + art.walk(&mut |n| live += n.appearance.effects.iter().filter(|e| e.id == "distort.transform").count()); + assert_eq!(live, 3, "each copy's instance keeps its random effect live"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + assert_eq!(unlike(&after), 0, "the expanded copies draw alike"); + assert!(differing(&before, &after, 64) < 200, "the copies stay where they are drawn"); +} + +/// A member's own Offset Path applies before the copying Transform effect of its group, which has +/// a stroke of its own, whether or not a shadow is listed before that Transform effect: the copy +/// scaled 200 % draws the offset square scaled, with or without a shadow at 0 % opacity. +#[test] +fn a_members_offset_path_applies_before_its_painted_groups_copies() { + let draw = |shadow: bool| { + let mut s = session(); + let mut ids = vec![]; + for x in [20, 40] { + ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 10}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + } + run(&mut s, "select.set", json!({"ids": [ids[0]]})); + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 5}})); + run(&mut s, "select.set", json!({"ids": ids})); + let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({})); + if shadow { + let fx = json!({"x": 10, "y": 0, "blur": 0, "opacity": 0, "mode": "normal", "color": "#00ff00"}); + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": fx})); + } + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}})); + let n = node(&s, g); + assert_eq!(vectorcraft_render::effects::outer_effects(&n).len() < n.appearance.effects.len(), shadow, "each copy carries the shadow"); + render(&s) + }; + let diff = differing(&draw(false), &draw(true), 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + /// Each copy of type's Transform effect draws the drop shadow listed before the effect under /// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 % /// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index c4438cf7e2..957a6c3c2c 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -224,6 +224,45 @@ fn shadows_and_glows_keep_their_blend_modes() { assert_eq!(modes, [vectorcraft_color::BlendMode::Multiply, vectorcraft_color::BlendMode::Screen]); } +/// Each copy of a group's Transform effect has its own image of the shadow listed before the +/// effect, under that copy: the squares' shadow (40..60) paints over their copy moved 30 pt right +/// (50..70), as on the canvas, and the copies' objects have ids of their own. +#[test] +fn each_copys_shadow_on_a_group_flattens_under_that_copy() { + let mut d = Document::new(200.0, 200.0); + let members = [20.0, 30.0].map(|x| Arc::new(rect(&mut d, Rect::new(x, 40.0, x + 10.0, 60.0), Color::rgb(1.0, 0.0, 0.0)))); + let mut g = Node::group(d.alloc_id(), members.to_vec()); + g.appearance.effects = vec![ + Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 20.0, "y": 0.0, "blur": 0.0, "opacity": 100.0, "mode": "normal", "color": "#00ff00"}), + visible: true, + }, + Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 1}), visible: true }, + ]; + add(&mut d, g); + let canvas = render(&d); + let flat = crate::flatten_raster_effects(&d).unwrap(); + let back = render(&flat); + let at = |r: &Rendered, x: usize| { + let i = (50 * r.width as usize + x) * 4; + (r.pixels[i], r.pixels[i + 1], r.pixels[i + 2]) + }; + for x in [55, 65, 85] { + let (want, got) = (at(&canvas, x), at(&back, x)); + assert!(want.0.abs_diff(got.0) < 32 && want.1.abs_diff(got.1) < 32 && want.2.abs_diff(got.2) < 32, "x {x}: {want:?} {got:?}"); + } + assert!(at(&back, 55).1 > 200 && at(&back, 55).0 < 60, "the squares' shadow over the copy: {:?}", at(&back, 55)); + let (mut seen, mut count) = (std::collections::HashSet::new(), 0); + for l in &flat.layers { + l.walk(&mut |n| { + seen.insert(n.id); + count += 1; + }); + } + assert_eq!(seen.len(), count, "each object has an id of its own"); +} + #[test] fn pdf_resolution_cap_warns_once_for_original_object_when_appearance_items_split() { let mut d = Document::new(300.0, 300.0); diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index e460aeb890..6f0242c662 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -151,6 +151,32 @@ fn style_names_are_unique() { assert_ne!(style(&s, "Y copy").id, style(&s, "Y").id); } +#[test] +fn duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 10.0); + run(&mut s, "graphicStyle.new", json!({"name": "S"})); + let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let before = names(&s); + // A style that is not last: the copy still goes after every other style. + let first = before[0].clone(); + assert_ne!(first, *before.last().unwrap()); + assert_eq!(run(&mut s, "graphicStyle.duplicate", json!({"name": first}))["name"], format!("{first} copy")); + let after = names(&s); + assert_eq!(after[..before.len()], before[..]); + assert_eq!(after.last(), Some(&format!("{first} copy"))); + let (src, copy) = (style(&s, &first), style(&s, &format!("{first} copy"))); + assert_eq!(copy.appearance, src.appearance); + assert_ne!(copy.id, src.id); + // Nothing is linked to the copy, and the source keeps its links. + assert!(linked(&mut s, &format!("{first} copy")).is_empty()); + assert_eq!(linked(&mut s, "S"), vec![a.0]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), before); + assert!(s.execute("graphicStyle.duplicate", &json!({"name": "nope"})).is_err()); + assert_eq!(names(&s), before); +} + /// Three rectangles: `a` (the source of style "S"), `b` and `c`, all linked to "S". fn linked_three(s: &mut Session) -> (NodeId, NodeId, NodeId) { let a = rect(s, 10.0); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 21c7fa8a15..7fc7285dbb 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4524,7 +4524,8 @@ proptest! { })?; match opened { Some(Ok(editing)) => prop_assert!(editing), - Some(Err(e)) => prop_assert_eq!(Some(e), page_error), + // The page's error, followed by why the editing data couldn't be read when it says. + Some(Err(e)) => prop_assert!(page_error.as_deref().is_some_and(|p| e == p || e.starts_with(&format!("{p}; its editing data couldn't be read either ("))), "{e}"), None => {} } } diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index a50c70c18d..d4c0e5c320 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -1,7 +1,10 @@ //! Clear deletes its exact targets, including compound members (#786). +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + use serde_json::json; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{NodeId, Selection}; use vectorcraft_engine::{EngineError, Session}; fn compound() -> (Session, NodeId, NodeId, NodeId) { @@ -225,3 +228,168 @@ fn clear_explicit_ids_preserves_unrelated_selection() { assert!(s.active().unwrap().doc.node(r2).is_none()); assert!(s.active().unwrap().selection.is_empty()); } + +fn rectangles(s: &mut Session, n: i64) -> Vec { + (0..n) + .map(|i| { + NodeId(s.execute("shape.rectangle", &json!({"x": 10 + 40 * i, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()) + }) + .collect() +} + +/// Clear with `ids` leaves the selection that removing each id on its own leaves: the other objects +/// in their order, their anchor and segment picks, a key object or key anchor that is not removed, +/// and the selected guides. Undo brings back the document and the selection, and Redo the result. +#[test] +fn clear_explicit_ids_leaves_what_removing_each_id_leaves() { + for key_anchor in [false, true] { + for removed in [[1, 4, 1, 6], [0, 2, 2, 6]] { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = rectangles(&mut s, 7); + s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap(); + let guide = s.active().unwrap().doc.ruler_guides()[0].id.unwrap(); + let sel = &mut s.active_mut().unwrap().selection; + // The seventh rectangle is not selected: Clear removes it from the document only. + sel.set(r[..6].iter().copied()); + sel.guides = vec![guide]; + for (id, anchor) in [(r[1], (0, 1)), (r[2], (0, 2)), (r[4], (0, 0)), (r[5], (0, 2))] { + sel.anchors.insert(id, BTreeSet::from([anchor, (0, 1)])); + } + for id in [r[2], r[5]] { + sel.segments.insert(id, BTreeSet::from([(0, 1)])); + } + if key_anchor { + sel.key_anchor = Some((r[4], (0, 0))); + } else { + sel.key = Some(r[4]); + } + let before = sel.clone(); + // The selection is one that `prune` keeps as it is, so Undo can restore it unchanged. + let mut pruned = before.clone(); + pruned.prune(&s.active().unwrap().doc); + assert_eq!(pruned, before); + let doc_before = s.active().unwrap().doc.clone(); + let ids: Vec = removed.iter().map(|i| r[*i]).collect(); + s.execute("edit.clear", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + let st = s.active().unwrap(); + let mut expected = before.clone(); + for id in &ids { + expected.remove(*id); + } + expected.prune(&st.doc); + assert_eq!(st.selection, expected, "key anchor {key_anchor}, removed {removed:?}"); + assert_eq!(st.selection.guides, vec![guide]); + assert!(ids.iter().all(|id| st.doc.node(*id).is_none())); + let doc_after = st.doc.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, doc_before); + assert_eq!(s.active().unwrap().selection, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, doc_after); + assert_eq!(s.active().unwrap().selection, expected); + } + } +} + +/// Cut of many selected objects puts each of them on the clipboard in paint order, removes them and +/// the selected guide, and leaves nothing selected. One Undo brings all of it back. +#[test] +fn cut_of_many_objects_takes_them_all_out_of_the_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = rectangles(&mut s, 40); + s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap(); + let guide = s.active().unwrap().doc.ruler_guides()[0].id.unwrap(); + let ids: Vec = r.iter().rev().map(|id| id.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let sel = &mut s.active_mut().unwrap().selection; + sel.guides = vec![guide]; + sel.key = Some(r[7]); + let before = sel.clone(); + let doc_before = s.active().unwrap().doc.clone(); + s.execute("edit.cut", &json!({})).unwrap(); + assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::>(), r); + let st = s.active().unwrap(); + assert!(r.iter().all(|id| st.doc.node(*id).is_none())); + assert!(st.doc.ruler_guides().is_empty()); + assert_eq!(st.selection, Selection::default()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, doc_before); + assert_eq!(s.active().unwrap().selection, before); +} + +/// Timings of taking the cut objects out of a selection of 2,000, 20,000 and 50,000 objects: one +/// [`Selection::remove`] per id, as Clear with `ids` did before, against one +/// [`Selection::remove_all`], for all of the objects and for every other one. The two run in turn +/// in one process, 7 times each, and the two results are compared field by field. It also times +/// Cut of every object, with Undo between the runs. Ignored by default; it prints its timings and +/// sets no bound on them: +/// `cargo test --release -p vectorcraft-engine --test it clear_selection_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn clear_selection_perf() { + fn ms(d: &[Duration]) -> String { + d.iter().map(|d| format!("{:.3}", d.as_secs_f64() * 1000.0)).collect::>().join(" ") + } + fn median(d: &mut [Duration]) -> f64 { + d.sort(); + d[d.len() / 2].as_secs_f64() * 1000.0 + } + for n in [2_000_i64, 20_000, 50_000] { + let mut b = vectorcraft_testkit::fixtures::DocBuilder::new(4000.0, 4000.0); + let r: Vec = (0..n) + .map(|i| { + let (x, y) = ((i % 400) as f64 * 10.0, (i / 400) as f64 * 10.0); + b.rect(vectorcraft_geom::Rect::new(x, y, x + 8.0, y + 8.0), vectorcraft_color::Color::rgb(0.2, 0.4, 0.6), |_| {}) + }) + .collect(); + let doc = b.build(); + let mut sel = Selection::default(); + sel.set(r.iter().copied()); + for id in r.iter().step_by(10) { + sel.anchors.insert(*id, BTreeSet::from([(0, 0)])); + } + sel.key = Some(r[r.len() / 2]); + for (what, ids) in [("all", r.clone()), ("every other", r.iter().copied().step_by(2).collect::>())] { + let (mut each, mut all) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let mut one_by_one = sel.clone(); + let start = Instant::now(); + for id in &ids { + one_by_one.remove(*id); + } + one_by_one.prune(&doc); + each.push(start.elapsed()); + let mut at_once = sel.clone(); + let start = Instant::now(); + at_once.remove_all(ids.iter().copied()); + at_once.prune(&doc); + all.push(start.elapsed()); + assert_eq!(at_once, one_by_one); + } + eprintln!("clear_selection_perf: {n} selected, {what} ({} ids), remove each ms: {}", ids.len(), ms(&each)); + eprintln!("clear_selection_perf: {n} selected, {what} ({} ids), remove_all ms: {}", ids.len(), ms(&all)); + eprintln!( + "clear_selection_perf: {n} selected, {what}: median remove each {:.3} ms, remove_all {:.3} ms", + median(&mut each), + median(&mut all) + ); + } + let mut s = Session::new(); + let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&doc, false)); + s.execute("document.open", &json!({"name": "perf.vectorcraft", "dataBase64": data})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let mut cut = Vec::new(); + for _ in 0..7 { + let start = Instant::now(); + s.execute("edit.cut", &json!({})).unwrap(); + cut.push(start.elapsed()); + assert!(s.active().unwrap().selection.objects.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects.len(), r.len()); + } + eprintln!("clear_selection_perf: {n} selected, edit.cut ms: {}", ms(&cut)); + eprintln!("clear_selection_perf: {n} selected, edit.cut median {:.3} ms", median(&mut cut)); + } +} diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index b35eb94fc0..d8a81461cb 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1413,6 +1413,153 @@ fn names_outside_windows_1252_are_replaced_and_kept_apart() { assert_eq!(inks(&read), want); } +/// `doc` written with [`Numbered::take`](super::writer::Numbered::take) numbering names by its +/// counters (`scanned` false) or by searching the names given for each number it tries. +fn export_numbering(doc: &Document, scanned: bool) -> LegacyAiOutput { + let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() }; + super::writer::SCANNED_NAMES.with(|s| s.set(scanned)); + let out = export_legacy_ai(doc, &o); + super::writer::SCANNED_NAMES.with(|s| s.set(false)); + out.unwrap() +} + +/// A linear gradient from `color` to white, named `swatch`. +fn gradient_from(color: Color, swatch: Option<&str>) -> Paint { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, color), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]); + let mut paint = GradientPaint::new(g); + paint.swatch = swatch.map(String::from); + Paint::Gradient(Box::new(paint)) +} + +/// A name the counters give is the first free `name 2`, `name 3`… for every order of names, those +/// already numbered (`Sky 2`, `Gradient 2 2`) and the empty name included. +#[test] +fn numbered_names_are_the_first_free_number() { + let bases = ["Gradient", "Gradient 2", "Gradient 3", "Gradient 2 2", "Sky", "Sky 2", "Sky 4", "?", "? 2", ""]; + let mut seed = 7u32; + let order: Vec<&str> = (0..3000) + .map(|_| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + bases[(seed >> 16) as usize % bases.len()] + }) + .collect(); + let names = |scanned: bool| { + super::writer::SCANNED_NAMES.with(|s| s.set(scanned)); + let mut numbered = super::writer::Numbered::default(); + let names: Vec = order.iter().map(|b| numbered.take((*b).to_string())).collect(); + super::writer::SCANNED_NAMES.with(|s| s.set(false)); + names + }; + let (counted, scanned) = (names(false), names(true)); + for (i, (c, s)) in counted.iter().zip(&scanned).enumerate() { + assert_eq!(c, s, "name {i}, {:?}", order[i]); + } + let given: std::collections::HashSet<&String> = counted.iter().collect(); + assert_eq!(given.len(), counted.len(), "every name is given once"); +} + +/// Gradient definitions and spot colors whose names collide are numbered as the file has always +/// numbered them: a gradient's swatch name or `Gradient`, then the first free number, with equal +/// gradients sharing a definition. The whole file is the same either way. +#[test] +fn colliding_gradient_and_spot_names_are_numbered_as_before() { + let mut doc = spots_and_gradient(&["\u{8d64}", "?", "\u{9752}", "? 2"], "Gradient 3"); + let layer = doc.layers[0].id; + let swatches = [None, None, Some("Gradient"), None, Some("\u{6e10}"), Some("?"), None, Some("Gradient 2"), Some("")]; + for (i, swatch) in swatches.into_iter().enumerate() { + let c = i as f32 / 10.0; + for repeat in 0..2 { + let x = 10.0 + 15.0 * i as f64; + let r = Rect::new(x, 60.0 + 15.0 * f64::from(repeat), x + 10.0, 70.0 + 15.0 * f64::from(repeat)); + let n = shape(&mut doc, shapes::rectangle(r), gradient_from(Color::cmyk(c, 1.0 - c, 0.5, 0.0), swatch), Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + } + let out = export_numbering(&doc, false); + let before = export_numbering(&doc, true); + let text = String::from_utf8(out.bytes).unwrap(); + assert_eq!(text, String::from_utf8(before.bytes).unwrap()); + assert_eq!(out.warnings, before.warnings); + let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect(); + let want = [ + "(Gradient 3)", + "(Gradient)", + "(Gradient 2)", + "(Gradient 4)", + "(Gradient 5)", + "(?)", + "(? 2)", + "(Gradient 6)", + "(Gradient 2 2)", + "(Gradient 7)", + ]; + assert_eq!(defined, want); + for name in want { + assert_eq!(text.matches(&format!("1 {name} ")).count(), if name == "(Gradient 3)" { 1 } else { 2 }, "{name}"); + } + assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}"); +} + +/// The time this thread has run, and how it was measured. +fn thread_time() -> (std::time::Duration, &'static str) { + if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + return (std::time::Duration::from_nanos(ns), "thread CPU time"); + } + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time") +} + +/// The time to write 1,500 objects that each have a gradient of their own and no swatch name, +/// with a few named ones that collide, numbering names by counters and by searching the names +/// given: the median of 7 runs of each, alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture many_unnamed_gradients`. +#[test] +#[ignore = "timing"] +fn many_unnamed_gradients_are_named_quickly() { + let mut doc = Document::new(1000.0, 1000.0); + let layer = doc.layers[0].id; + let count = 1500u16; + for i in 0..count + 4 { + let swatch = match i { + 0 => Some("Gradient 3"), + 1 => Some("Gradient"), + 2 | 3 => Some("Sky"), + _ => None, + }; + let t = f32::from(i) / f32::from(count + 4); + let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40) * 25.0); + let paint = gradient_from(Color::rgb(t, 1.0 - t, (t * 7.0).fract()), swatch); + let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let mut times = [vec![], vec![]]; + let mut files: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [false, true].into_iter().enumerate() { + let (start, h) = thread_time(); + let out = export_numbering(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + let defs = String::from_utf8_lossy(&out.bytes).lines().filter(|l| l.ends_with(" Bd")).count(); + assert_eq!(defs, usize::from(count) + 4); + files[k].get_or_insert(out.bytes); + } + } + assert_eq!(files[0], files[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("{} gradient definitions, median of 7 runs ({how}):", count + 4); + println!("| naming | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["counters", "search of the names given"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// #6502: the legacy writer gives Yellow, Magenta and Cyan (presets 4, 5 and 6) the file's /// indexes 6, 4 and 5, and they open as the same presets. #[test] diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 0551d1821c..536940b9f6 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -15,6 +15,9 @@ use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPP thread_local! { /// How many times [`Writer::coverage`] has worked out an image's coverage on this thread. pub(super) static COVERAGE_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`Numbered::take`] numbers names on this thread by searching the names given so + /// far, one number at a time, for each number it tries. + pub(super) static SCANNED_NAMES: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel. @@ -66,6 +69,10 @@ pub(super) struct Writer<'a> { whole_images: std::collections::HashMap>>, /// Writing a graph's art with its records: a graph inside it is written as its art. in_graph: bool, + /// The names of [`Self::gradients`]. + gradient_names: Numbered, + /// The names spot colors are written with ([`Self::spot`]). + spot_written: Numbered, } impl<'a> Writer<'a> { @@ -94,6 +101,8 @@ impl<'a> Writer<'a> { last_coverage: None, whole_images: std::collections::HashMap::new(), in_graph: false, + gradient_names: Numbered::default(), + spot_written: Numbered::default(), } } @@ -155,12 +164,7 @@ impl<'a> Writer<'a> { Some((_, w)) => w.clone(), None => { let base = self.latin_name(name, TITLE_AND_COLOR_NAMES); - let mut written = base.clone(); - let mut i = 1; - while self.spot_names.iter().any(|(_, w)| *w == written) { - i += 1; - written = format!("{base} {i}"); - } + let written = self.spot_written.take(base); self.spot_names.push((name.to_string(), written.clone())); written } @@ -823,14 +827,8 @@ impl<'a> Writer<'a> { if let Some((name, _)) = self.gradients.iter().find(|(_, d)| d == g) { return name.clone(); } - let taken = |n: &str, defs: &[(String, Gradient)]| defs.iter().any(|(m, _)| m == n); let base = self.latin_name(swatch.filter(|s| !s.is_empty()).unwrap_or("Gradient"), TITLE_AND_COLOR_NAMES); - let mut name = base.clone(); - let mut i = 1; - while taken(&name, &self.gradients) { - i += 1; - name = format!("{base} {i}"); - } + let name = self.gradient_names.take(base); self.gradients.push((name.clone(), g.clone())); name } @@ -1244,3 +1242,46 @@ impl<'a> Writer<'a> { s.push_str("%AI5_EndRaster\nF\n"); } } + +/// Names kept apart: a name already given is numbered, as the first free `name 2`, `name 3`… +#[derive(Default)] +pub(super) struct Numbered { + taken: std::collections::HashSet, + /// The number to try first for each name already given, after the numbers it was given. + next: std::collections::HashMap, + /// The names given, in order, for [`SCANNED_NAMES`]. + #[cfg(test)] + given: Vec, +} + +impl Numbered { + /// `base`, or the first free `base 2`, `base 3`… when `base` is taken; it is then taken. + pub(super) fn take(&mut self, base: String) -> String { + #[cfg(test)] + if SCANNED_NAMES.with(std::cell::Cell::get) { + let mut name = base.clone(); + let mut i = 1; + while self.given.contains(&name) { + i += 1; + name = format!("{base} {i}"); + } + self.given.push(name.clone()); + return name; + } + let name = if self.taken.contains(&base) { + // Names are never given back, so every number below `from` is still taken. Of the + // numbers `from..=tries`, at least one is free. + let from = self.next.get(&base).copied().unwrap_or(2); + let tries = from.saturating_add(self.taken.len()); + let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries); + self.next.insert(base.clone(), i.saturating_add(1)); + format!("{base} {i}") + } else { + base + }; + self.taken.insert(name.clone()); + #[cfg(test)] + self.given.push(name.clone()); + name + } +} diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 9cef615783..a5f93a2a76 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -87,7 +87,7 @@ pub use import::{ pub use pages::reads_of; pub use pages::{ IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, - is_postscript, open_pdf, + is_postscript, open_pdf, read_illustrator_data_without_pdf_part, }; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 683a14d1c3..64e6217148 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -502,25 +502,42 @@ pub struct IllustratorData { /// objects, and only the private data streams are read, with the same limits. `None` when the /// file itself can't be opened, or as for [`illustrator_data`]. pub fn illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Option { - let pdf = open_structural_with_options(bytes, password, &open_options()).ok()?; - let data = private_data(&pdf)?; - let page = pdf.pages().first()?; + read_illustrator_data_without_pdf_part(bytes, password).ok().flatten() +} + +/// [`illustrator_data_without_pdf_part`], with why the private data can't be read: `Ok(None)` +/// when the file can't be opened or has no private data, `Err` (for a note, such as "it is larger +/// than 256 MB") when it has private data that can't be read. +pub fn read_illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Result, String> { + let Ok(pdf) = open_structural_with_options(bytes, password, &open_options()) else { return Ok(None) }; + let Some(data) = read_private_data(&pdf)? else { return Ok(None) }; + let Some(page) = pdf.pages().first() else { return Ok(None) }; // (The page transform is in points: it applies the `UserUnit`.) let trim = frame(page, CropTo::Trim).1; - Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) }) + Ok(Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) })) } /// The private data of `pdf`'s first page, as [`illustrator_data`] reads it. fn private_data(pdf: &Pdf) -> Option> { - let page = pdf.pages().first()?; - let private = page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")?; + read_private_data(pdf).ok().flatten() +} + +/// [`private_data`], with why a private data stream can't be read ([`inflated`]). +fn read_private_data(pdf: &Pdf) -> Result>, String> { + let Some(private) = pdf + .pages() + .first() + .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")) + else { + return Ok(None); + }; let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" }; let mut data = vec![]; for n in 1..=100_000u32 { let Some(stream) = private.get::>(format!("{key}{n}").as_bytes()) else { break }; - data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len())?); + data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len()).map_err(|why| why.to_string())?); } - (!data.is_empty()).then_some(data) + Ok((!data.is_empty()).then_some(data)) } /// Does the PDF's first page carry an editor's copy of the art: a PDF-compatible `.ai` @@ -538,10 +555,12 @@ fn has_private_data_keys(pdf: &Pdf) -> bool { /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's /// `decoded()`, which has no limit, so a stream of zeros can't grow to the size of the memory. Only a /// stream that is plain or only deflated is read (the private data is no other), without decode -/// parameters; else, or when it is larger once decoded, `None`. A filter the reader doesn't know -/// counts as another filter. -fn inflated(stream: &Stream<'_>, most: usize) -> Option> { +/// parameters; else, or when it is larger once decoded, `Err` with why. A filter the reader +/// doesn't know counts as another filter. +fn inflated(stream: &Stream<'_>, most: usize) -> Result, String> { use std::io::Read; + let unread = || "it is stored in a form that isn't read".to_string(); + let too_large = || format!("it is larger than {} MB", MAX_PRIVATE >> 20); let dict = stream.dict(); let named = |key: &[u8]| match dict.get::>(key) { None | Some(Object::Null(_)) => Some(0), @@ -555,24 +574,28 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Option> { Some(_) => true, }; if params(b"DecodeParms") || params(b"DP") { - return None; + return Err(unread()); } let filters = stream.filters(); // (The reader leaves out the filters it doesn't know.) - if named(b"Filter")?.max(named(b"F")?) != filters.len() { - return None; + if named(b"Filter").zip(named(b"F")).is_none_or(|(a, b)| a.max(b) != filters.len()) { + return Err(unread()); } let raw = stream.raw_data(); let mut out = vec![]; - let limit = u64::try_from(most).ok()?.checked_add(1)?; + let limit = u64::try_from(most).ok().and_then(|m| m.checked_add(1)).ok_or_else(too_large)?; match filters.as_slice() { [] if raw.len() <= most => out.extend_from_slice(&raw), + [] => return Err(too_large()), [craft_pdf::syntax::Filter::FlateDecode] => { - flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).ok()?; + flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).map_err(|_| "its zlib compression is damaged".to_string())?; } - _ => return None, + _ => return Err(unread()), } - (out.len() <= most).then_some(out) + if out.len() > most { + return Err(too_large()); + } + Ok(out) } /// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)? diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 86e1a88fb1..c0f9dfc970 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -446,7 +446,16 @@ fn private_data_reads_without_a_pdf_part_that_cant_be_read() { let pdf = pdf_with_catalog(std::slice::from_ref(&page), &[&first, &two], "", None); assert!(illustrator_data(&pdf, None).is_none(), "{odd}"); assert!(illustrator_data_without_pdf_part(&pdf, None).is_none(), "{odd}"); + let why = read_illustrator_data_without_pdf_part(&pdf, None); + assert_eq!(why, Err("it is stored in a form that isn't read".to_string()), "{odd}"); } + // Damaged zlib data, and a file without private data or that isn't a PDF. + let damaged = stream("/Filter /FlateDecode", "not zlib"); + let pdf = pdf_with_catalog(std::slice::from_ref(&page), &[&damaged, &two], "", None); + assert_eq!(read_illustrator_data_without_pdf_part(&pdf, None), Err("its zlib compression is damaged".to_string())); + let bare = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "")], &[], "", None); + assert_eq!(read_illustrator_data_without_pdf_part(&bare, None), Ok(None)); + assert_eq!(read_illustrator_data_without_pdf_part(b"not a pdf", None), Ok(None)); } /// Art in ordinary tags nested inside a layer's sequence goes to that layer; the group is kept diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index aefe50a947..3f51f63bcf 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -791,9 +791,11 @@ pub(crate) fn three_d_art_bounds(symbols: &SymbolBoxes, art: &Node) -> Option Rect { - let o = outset(symbols, &n.appearance.effects, b); + let o = outset(symbols, effects::outer_effects(n), b); b.inflate(o, o) } diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 13fc9c0cbf..6eb13767d8 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1350,6 +1350,46 @@ fn each_copy_of_a_fills_or_strokes_transform_draws_its_own_shadow() { assert_eq!(img.pixel(60, 80), [255, 255, 255, 255], "inside the copy's stroke shadow"); } +/// Each copy of a group's or layer's Transform effect draws the drop shadow listed before the +/// effect under itself, of all its members together and scaled with it: two red squares side by +/// side (10..30 together) have one green shadow 20 pt to their right, and their copy scaled 200 % +/// and moved 60 pt down (0..40 across, 60..100 down) has its own 40 pt to its right. The bounds +/// reach as far as the copy's shadow, and no further. +#[test] +fn each_copy_of_a_groups_or_layers_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1})); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + for layer in [false, true] { + let mut d = Document::new(100.0, 100.0); + let members: Vec> = [Rect::new(10.0, 10.0, 20.0, 30.0), Rect::new(20.0, 10.0, 30.0, 30.0)] + .into_iter() + .map(|r| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), red.clone()))) + .collect(); + if layer { + let l = Arc::make_mut(&mut d.layers[0]); + if let Some(ch) = l.children_mut() { + *ch = members; + } + l.appearance.effects = vec![shadow.clone(), copies.clone()]; + } else { + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = vec![shadow.clone(), copies.clone()]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + } + let img = render(&d); + assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "layer {layer}: the squares"); + assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "layer {layer}: the squares' shadow"); + assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "layer {layer}: the copy"); + assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "layer {layer}: the copy's shadow, 40 pt to its right"); + assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "layer {layer}: past the copy's shadow"); + let n = if layer { d.layers[0].clone() } else { d.layers[0].children().unwrap()[0].clone() }; + let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), &n).unwrap(); + assert!((b.x1 - 80.0).abs() < 1e-9, "layer {layer}: {b:?}"); + } +} + /// Each copy of an image's Transform effect draws the drop shadow listed before the effect under /// itself, scaled with it: the red image (20..50) has its green shadow 10 pt to its right, and its /// copy scaled 50 % and moved 40 pt down (27.5..42.5 across, 67.5..82.5 down) has its own 5 pt to diff --git a/crates/testkit/src/ai.rs b/crates/testkit/src/ai.rs index b560255e32..50af82d04c 100644 --- a/crates/testkit/src/ai.rs +++ b/crates/testkit/src/ai.rs @@ -338,6 +338,12 @@ pub fn ai_with_entries_and_content(private: &[u8], page: &str, entries: &str, co with_private(private, page, "AIPrivateData", entries, content) } +/// [`ai_with_content`] with `streams` more in the dictionary of each private data stream +/// (`/Filter /Bogus `). +pub fn ai_with_private_streams(private: &[u8], page: &str, content: &str, streams: &str) -> Vec { + with_private_streams(private, page, "AIPrivateData", "", content, streams) +} + /// A PDF saved with Illustrator's editing data: [`ai`]'s file with the two streams under /// `AIPDFPrivateData1` and `AIPDFPrivateData2`. These key names were seen in the PDF attached to /// #868, and nothing else of that file is used; ExifTool's PDF tag table lists them too @@ -354,6 +360,11 @@ pub fn pdf_with_content(private: &[u8], page: &str, content: &str) -> Vec { /// The file of [`ai`] and [`pdf`], with `private` in the streams `{key}1` and `{key}2`, `entries` /// more in the page dictionary and `content` more in its content stream's dictionary. fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: &str) -> Vec { + with_private_streams(private, page, key, entries, content, "") +} + +/// [`with_private`] with `streams` more in each private data stream's dictionary. +fn with_private_streams(private: &[u8], page: &str, key: &str, entries: &str, content: &str, streams: &str) -> Vec { let (first, second) = private.split_at(private.len() / 2); let stream = |part: &[u8], more: &str| { let mut s = format!("<< /Length {} {more}>>\nstream\n", part.len()).into_bytes(); @@ -371,8 +382,8 @@ fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: & ) .into_bytes(), stream(page.as_bytes(), content), - stream(first, ""), - stream(second, ""), + stream(first, streams), + stream(second, streams), ]; let mut out = b"%PDF-1.5\n".to_vec(); let mut offsets = vec![]; diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index e9bee961f8..0082a01a99 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -25,8 +25,9 @@ //! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]). //! A Cmd/Ctrl+Shift double-click with either one releases the ruler guide or guide path under the //! pointer ([`release_guide_at`]). -//! Direct Selection also edits a blend's spine: drag its points (Shift-click picks several, which -//! drag together; a key object on a point moves with it) and, once a point is clicked, its +//! Direct Selection also edits a blend's spine: drag its points (Shift-click and, on a selected +//! blend, the marquee pick several, which drag together; a key object on a point moves with it) +//! and, once a point is clicked, its //! handles; and the points of selected gradient meshes //! and of mesh and warp envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several, //! a click on a gradient mesh's line picks its two ends and one inside a patch the four points @@ -192,7 +193,8 @@ pub struct DirectSelectionTool { moved: Option, /// The spine point last clicked (blend, anchor): its handles show and can be dragged. spine: Option<(NodeId, usize)>, - /// Other points of that spine picked with it (Shift-click adds or takes one away); dragging + /// Other points of that spine picked with it (Shift-click adds or takes one away, and a + /// marquee picks those inside it); dragging /// a picked point moves them all (#5285). spine_more: Vec, mesh: MeshEdit, @@ -915,6 +917,10 @@ impl Tool for DirectSelectionTool { if let Some(out) = self.press_hidden(cx, ev, p) { return out; } + // The spine points picked before stay picked while the marquee is drawn: its + // release replaces them (with Shift, toggles them), and Escape keeps them. + self.spine = held; + self.spine_more = if held.is_some() { more } else { vec![] }; self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false, whole: ev.mods.alt }; vec![] } @@ -1641,12 +1647,14 @@ impl DirectSelectionTool { return vec![]; } self.frame.clear(); + (self.spine, self.spine_more) = (None, vec![]); return vec![Action::Exec("select.none".into(), json!({}))]; } // With Group Selection's enclosed marquee, the tool selects the objects inside it // (members of groups too), each whole, as a click selects one; with Group Selection's // marquee or an Alt-marquee, every object it touches, each whole (#8047). if enclosed || whole || self.group { + (self.spine, self.spine_more) = (None, vec![]); let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); @@ -1702,6 +1710,33 @@ impl DirectSelectionTool { } } } + // Direct Selection: the points of a selected blend's spine inside the rect are picked, on + // the topmost such blend; with Shift they are toggled. The blend stays selected. A plain + // marquee that holds none of them drops the points picked before. + let mut spined: Option = None; + if !self.group { + let found = spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + let inside: BTreeSet = path.anchors().filter(|(s, _, a)| *s == 0 && r.contains(a.p)).map(|(_, i, _)| i).collect(); + (!inside.is_empty()).then_some((id, inside)) + }); + match found { + Some((id, inside)) => { + let held = self.spine.filter(|(h, _)| toggle && *h == id); + let before: BTreeSet = held.map(|(_, a)| self.spine_more.iter().copied().chain([a]).collect()).unwrap_or_default(); + let picked: BTreeSet = if toggle { before.symmetric_difference(&inside).copied().collect() } else { inside }; + let focus = held.map(|(_, a)| a).filter(|a| picked.contains(a)).or_else(|| picked.last().copied()); + self.spine = focus.map(|a| (id, a)); + self.spine_more = picked.into_iter().filter(|a| Some(*a) != focus).collect(); + spined = Some(id); + if !toggle { + sel.push((id, vec![])); + } + } + None if !toggle => (self.spine, self.spine_more) = (None, vec![]), + // With Shift, the blend holding the picked points stays selected with them. + None => spined = self.spine.map(|(id, _)| id), + } + } let mut marked: BTreeMap> = if toggle { self.frame_anchors(cx).into_iter().map(|(id, v)| (id, v.into_iter().collect())).collect() } else { BTreeMap::new() }; for (id, inside) in &framed { @@ -1721,7 +1756,7 @@ impl DirectSelectionTool { // the marquee touches them, as with the Selection tool (#927). for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); - if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) { + if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) { sel.push((id, vec![])); } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 20f9df51f2..a0fabb9cb8 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -246,6 +246,137 @@ fn shift_click_picks_several_spine_points_which_drag_together() { assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 0 && v.get("with").is_none()), "{a:?}"); } +/// [`blend_doc`] with a spine through (110, 310), (160, 310) and (210, 310). +fn blend_doc_with_three_spine_points() -> (vectorcraft_doc::Document, NodeId) { + let (mut d, g, _) = blend_doc(); + let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(160.0, 310.0), Point::new(210.0, 310.0)], false); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![0, 2]); + (d, g) +} + +/// A marquee drawn with Direct Selection from `from` to `to`, released. +fn spine_marquee(t: &mut DirectSelectionTool, cx: &ToolContext, from: (f64, f64), to: (f64, f64), mods: Mods) -> Vec { + assert_eq!(t.pointer(cx, &PointerEvent::new(PointerKind::Down, from.0, from.1).with_mods(mods)), vec![]); + t.pointer(cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1).with_mods(mods)); + assert!(t.overlays(cx).iter().any(|o| matches!(o, Overlay::Marquee(_))), "a marquee"); + t.pointer(cx, &PointerEvent::new(PointerKind::Up, to.0, to.1).with_mods(mods)) +} + +/// A Direct Selection marquee picks the points of a selected blend's spine inside it, which then +/// drag together, and keeps the blend selected; a marquee around none of them drops the picks. +#[test] +fn marquee_picks_selected_blend_spine_points_which_drag_together() { + let (d, g) = blend_doc_with_three_spine_points(); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let filled = |t: &DirectSelectionTool| t.overlays(&cx).iter().filter(|o| matches!(o, Overlay::Anchor { filled: true, .. })).count(); + let mut t = DirectSelectionTool::new(false); + // Around (160, 310) and (210, 310), the second on the rect's edge. + let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (160.0, 290.0), Mods::default()); + assert!( + matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["mode"] == "set" && v["items"].as_array().is_some_and(|i| i.iter().any(|i| i["id"] == g.0))), + "the blend stays selected: {a:?}" + ); + assert_eq!(filled(&t), 2, "both picked points show"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 330.0)); + assert_eq!( + a.last(), + Some(&Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": g.0, "anchor": 2, "x": 210.0, "y": 330.0, "with": [1]}))) + ); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 330.0)), vec![Action::Commit]); + // A marquee around none of the points drops them. + spine_marquee(&mut t, &cx, (300.0, 330.0), (240.0, 290.0), Mods::default()); + assert_eq!((t.spine, filled(&t)), (None, 0)); +} + +/// With Shift, a Direct Selection marquee toggles the spine points inside it: a picked one leaves, +/// another joins, and those outside it keep their state; the blend is not toggled away. +#[test] +fn shift_marquee_toggles_selected_blend_spine_points() { + let (d, g) = blend_doc_with_three_spine_points(); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0)); + let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (150.0, 290.0), shift); + assert!( + matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["items"].as_array().is_some_and(|i| !i.iter().any(|i| i["id"] == g.0))), + "the blend is not toggled: {a:?}" + ); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![])); + spine_marquee(&mut t, &cx, (130.0, 330.0), (90.0, 290.0), shift); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0])); + // A Shift-marquee around none of them keeps them, and keeps the blend selected when it + // touches the blend's art. + spine_marquee(&mut t, &cx, (300.0, 330.0), (240.0, 290.0), shift); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0])); + let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (205.0, 315.0), shift); + assert!( + matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["items"].as_array().is_some_and(|i| !i.iter().any(|i| i["id"] == g.0))), + "the blend is not toggled: {a:?}" + ); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0])); +} + +/// A Direct Selection marquee does not pick the spine points of a blend that is not selected, or +/// of a selected blend that is locked or hidden. +#[test] +fn marquee_skips_unselected_locked_and_hidden_blend_spines() { + let (d, g) = blend_doc_with_three_spine_points(); + let p = paint(); + let mut s = Selection::default(); + let none = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + spine_marquee(&mut t, &none, (230.0, 330.0), (150.0, 290.0), Mods::default()); + assert_eq!(t.spine, None, "not selected"); + s.set([g]); + for lock in [true, false] { + let mut d = d.clone(); + let Some(n) = d.node_mut(g) else { panic!("blend") }; + if lock { + n.locked = true; + } else { + n.visible = false; + } + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + spine_marquee(&mut t, &c, (230.0, 330.0), (150.0, 290.0), Mods::default()); + assert_eq!(t.spine, None, "locked: {lock}"); + } + // The same marquee on the selected blend picks them. + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + spine_marquee(&mut t, &c, (230.0, 330.0), (150.0, 290.0), Mods::default()); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![1])); +} + +/// Escape during a Direct Selection marquee cancels it and keeps the spine points picked before. +#[test] +fn escape_cancels_a_marquee_and_keeps_the_picked_spine_points() { + let (d, g) = blend_doc_with_three_spine_points(); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 330.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 290.0)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 290.0)), vec![]); + assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 1)), vec![])); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Anchor { filled: true, .. })), "the picked point shows"); +} + /// #1111: the Anchor Point tool bends a selected blend's straight spine; Direct Selection /// reshapes a curved spine segment and leaves a straight one alone, as it does a path's. #[test] diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 9c6bcadd71..e49fa9bfc7 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -22,11 +22,7 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { - ids.iter().filter_map(|id| doc.node(*id)).any(|n| { - let mut found = false; - vectorcraft_doc::swatches::node_colors(n, &mut |_, _| found = true); - found - }) + ids.iter().filter_map(|id| doc.node(*id)).any(vectorcraft_doc::swatches::node_has_colors) } /// The bounds of the artboards the Artboard tool has selected ([`crate::panels::artboards::picked`]). diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 885ba3dcc6..cc65044dfb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11228,6 +11228,28 @@ fn the_task_bar_recolors_coloured_art() { assert!(app.ui.dialog.is_none(), "no Recolor button without colours"); } +/// Recolor Artwork shows in the bars when any selected object has a color, whichever of them it is, +/// and not for an empty selection or ids that are gone. +#[test] +fn has_colors_looks_at_every_selected_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x: i32| { + vectorcraft_doc::NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()) + }; + let (blank, colored) = (rect(10), rect(80)); + s.execute("paint.setFill", &json!({"ids": [blank.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [blank.0], "none": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [colored.0], "color": "#cc3322"})).unwrap(); + let doc = &s.active().unwrap().doc; + let gone = vectorcraft_doc::NodeId(u64::MAX); + assert!(!has_colors(doc, &[]), "nothing selected"); + assert!(!has_colors(doc, &[gone]), "an id that is gone"); + assert!(!has_colors(doc, &[blank, gone])); + assert!(has_colors(doc, &[blank, colored]), "the color is on the second object"); + assert!(has_colors(doc, &[colored, blank, gone]), "the color is on the first object"); +} + /// The Contextual Task Bar's Lock button locks the selected member in isolation mode and the /// selected group outside isolation mode. #[test] diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index b807bc5274..b761383752 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -398,6 +398,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }) .or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)}))) .or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d))); + let corner_radius = if d.kind == "roundedRectangle" { Some(rounded_radius(app, d)?) } else { None }; let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); let (bx, by) = box_origin(d); let (id, params) = match d.kind.as_str() { @@ -462,7 +463,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } _ => ( "shape.rectangle", - json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "radius": d.f64("radius", 0.0)}), + json!({ + "x": bx, + "y": by, + "width": d.f64("width", 100.0), + "height": d.f64("height", 100.0), + "radius": corner_radius.unwrap_or_else(|| d.f64("radius", 0.0)), + }), ), }; // On the active plane while the perspective grid shows, sized in plane units from the click; @@ -484,9 +491,21 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(options) = options { app.run("tool.setOption", json!({"tool": d.kind, "values": options}))?; } + // The radius of the rounded rectangle drawn is General › Corner Radius from then on. + if let Some(r) = corner_radius.filter(|r| *r != app.session.prefs.corner_radius) { + app.run("prefs.set", json!({"key": "cornerRadius", "value": r}))?; + } Ok(result) } +/// The Rounded Rectangle dialog's radius in points, checked as General › Corner Radius checks it +/// (an error leaves the dialog open and draws nothing). Without the field, the preference. +fn rounded_radius(app: &VectorcraftApp, d: &Dialog) -> Result { + let r = if d.fields.contains_key("radius") { d.f64("radius", f64::NAN) } else { app.session.prefs.corner_radius }; + vectorcraft_engine::cmd::prefscmds::validate("cornerRadius", &json!(r))?; + Ok(r) +} + #[cfg(test)] mod tests { use super::*; @@ -524,6 +543,48 @@ mod tests { assert_eq!(box_origin(&fields(true)), (80.0, 40.0)); } + /// The Rounded Rectangle click dialog opens on General › Corner Radius, and OK makes the radius + /// typed (in any unit) that preference: the next dialog and the tool's next drag use it. + #[test] + fn rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("tool.select", json!({"tool": "roundedRectangle"})).unwrap(); + app.run("prefs.set", json!({"key": "cornerRadius", "value": 20})).unwrap(); + + super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0})); + let d = app.ui.dialog.as_mut().expect("Rounded Rectangle dialog"); + assert_eq!((d.kind.as_str(), d.f64("radius", 0.0)), ("roundedRectangle", 20.0)); + d.fields.insert("radius".into(), json!("0.5 in")); + super::super::confirm(&mut app).unwrap(); + + assert!(app.ui.dialog.is_none()); + let n = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].clone(); + assert_eq!(crate::panels::corner_radius(&app, &n), Some(36.0)); + assert_eq!(app.session.prefs.corner_radius, 36.0); + assert_eq!(app.session.tool_options_of("roundedRectangle")["cornerRadius"], json!(36.0)); + super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); + } + + /// A radius General › Corner Radius would refuse leaves the dialog open, draws nothing and + /// keeps the preference. + #[test] + fn rounded_rectangle_click_dialog_refuses_a_radius_out_of_range() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let before = app.session.prefs.corner_radius; + for bad in [json!(-1), json!(1297), json!("19 in"), json!("wide")] { + super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), bad.clone()); + assert!(super::super::confirm(&mut app).is_err(), "{bad}"); + assert!(app.ui.dialog.is_some(), "{bad}"); + assert!(app.session.doc().unwrap().doc.layers[0].children().unwrap().is_empty(), "{bad}"); + assert_eq!(app.session.prefs.corner_radius, before, "{bad}"); + app.ui.dialog = None; + } + } + /// Turn the link on or off as its button or `ui.dialog.set` does, then apply it as the form /// does on its next frame; what [`link_changed`] returned. fn turn(d: &mut Dialog, on: bool) -> Option { diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index bf65dd4894..6dbcfe28ce 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -18,7 +18,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}), ), - "roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})), + // The radius starts at General › Corner Radius, which OK sets to the radius typed. + "roundedRectangle" => { + let radius = format!("{} pt", app.session.prefs.corner_radius); + Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": radius})) + } "polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})), "star" => { Dialog::new(kind, json!({"x": x, "y": y, "radius1": "50 pt", "radius2": "25 pt", "points": app.session.tool_options_of(kind)["points"]})) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b27a198fc1..754ae856bd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -354,7 +354,7 @@ font-technology Variable Променливи Built-in presets are read-only: New… starts an editable copy. Вградените предварителни настройки са само за четене: „Ново…“ създава редактируемо копие. Built-in presets don't change: New makes a copy you can edit. Вградените предварителни настройки не се променят: „Ново“ създава копие за редактиране. Built-in presets don't change: New… starts an editable copy. Вградените предварителни настройки не се променят: „Ново…“ създава редактируемо копие. - Bulge… Издуване… + Bulge… Изпъкване… Bullet Булет Bullets Булети Bullets and Numbering Булети и номериране @@ -1485,7 +1485,7 @@ font-technology Variable Променливи Guides & Grid Водачи и мрежа H Spacing: Хоризонтално разстояние: H: Х: - Hair Space Тънък интервал + Hair Space Най-тънък интервал Hand Tool Инструмент „Ръка“ Hand-Drawn Ръчно рисувани Painted and Sketched Рисувани и скицирани @@ -2994,7 +2994,7 @@ digits Malayalam Малаялам Opening it left out what VectorCraft can't read yet ({what}), so replacing it loses that for good. Save under another name to keep it. Отварянето му пропусна това, което VectorCraft все още не може да прочете ({what}), така че замяната му го губи завинаги. Запазете под друго име, за да го запазите. “{name}” already exists. Replace it? „{name}“ вече съществува. Да бъде ли заменен? The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. Името в панела за запазване беше „{typed}“, а VectorCraft добави разширението на типа файл. Замяната на файла презаписва съдържанието му. - Revolve… Завъртане… + Revolve… Завъртане около ос… RGB Color RGB цвят Right Вдясно Right Grid: Дясна мрежа: @@ -3830,7 +3830,7 @@ digits Malayalam Малаялам Reverse Traps Обратни застъпвания Precision Точност Remove Redundant Points Премахване на излишните точки - Trim Изрязване + Trim Подрязване Trim mark weight: Дебелина на маркировките за изрязване: Trim marks Маркировки за изрязване Trim View Изглед на изрязване @@ -5167,7 +5167,7 @@ effect Soft Меко On Both Sides От двете страни Short Кратко Full Width Пълна ширина - Distort Изкривяване + Distort Деформиране Diffuse Glow… Дифузно светещ… Glass… Стъкло… Ocean Ripple… Океански вълнички… @@ -5769,8 +5769,8 @@ lighting Light Светлина x Height Височина на x ▾ Default Actions ▾ Действия по подразбиране ⚠ {chord} was already used by {names} — it has been removed there. Внимание: Комбинацията {chord} вече се използва от {names} — премахната е там. -@id file.close file.close -@id pathfinder.add pathfinder.add +@id file.close Затваряне +@id pathfinder.add Обединяване @msg give corners of the path: anchors between two straight sides дай ъглите на пътя: опорни точки между две прави страни @msg this kind of brush has no options dialog yet този вид четка засега няма диалогов прозорец с настройки @plural {n} PR|{n} PRs {n} PR|{n} PR-а diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index df8c34eeeb..6c741f000f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -384,7 +384,7 @@ Insert Whitespace Character Umetni znak razmaka Em Space Široki razmak (em) En Space Polu-široki razmak (en) - Hair Space Tanki razmak + Hair Space Najtanji razmak Sixth Space Šestina razmaka Thin Space Tanki razmak Nonbreaking Space Neprelomivi razmak diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a3f6252a3f..2f823c2db0 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5035,7 +5035,7 @@ digits Malayalam Malaiàlam Triangle Triangle Triangle (open) Triangle (obert) Triangle to Bar Triangle a barra - Trim Retalla + Trim Poda Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Retalla la geometria coberta en expandir l’aparença. La previsualització en directe manté tota la superfície. Les pintures transparents i les superfícies que superen els límits de visibilitat conserven totes les cares. Trim mark weight: Gruix de les marques de retall: Trim marks Marques de retall @@ -6440,6 +6440,25 @@ liquify-list-end {0}, {1} {0} i {1} @msg a 3D effect on a group's fill or stroke draws nothing un efecte 3D al farciment o al traç d’un grup no dibuixa res @msg a 3D effect on a group's fill or stroke draws nothing to export un efecte 3D al farciment o al traç d’un grup no dibuixa res per exportar @msg The 3D object is too complex to export L’objecte 3D és massa complex per exportar-lo +@msg give one element indica un element +@msg the element needs an id, the filter's name l’element necessita un id, el nom del filtre +@msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG té com a màxim {MAX_NAME} caràcters +@msg <{_1}> isn't an element of an SVG filter <{_1}> no és un element d’un filtre SVG +@msg an SVG filter has no event attributes such as {_1} un filtre SVG no té atributs d’esdeveniment com ara {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs les imatges d’un filtre SVG són URL data: en PNG, JPEG, GIF o WebP +@msg the SVG filter isn't valid XML: {e} el filtre SVG no és un XML vàlid: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves de feTurbulence és com a màxim {MAX_OCTAVES} +@msg {what} is at most {max} {what} és com a màxim {max} +@msg feConvolveMatrix's order order de feConvolveMatrix +@msg feMorphology's radius radius de feMorphology +@msg a blur's stdDeviation stdDeviation d’un desenfocament +@msg the SVG filter has no primitives el filtre SVG no té primitives +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives un filtre SVG té com a màxim {MAX_PRIMITIVES} primitives +@msg the SVG filter is too large once its attributes are written out el filtre SVG és massa gran un cop escrits els seus atributs +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all les imatges d’un filtre SVG tenen com a màxim {MAX_IMAGE_PIXELS} píxels en total +@msg the SVG filter can't be drawn: check its primitives and their inputs no es pot dibuixar el filtre SVG: comprova’n les primitives i les seves entrades +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep els elements d’un filtre SVG s’imbriquen com a màxim {MAX_DEPTH} nivells +@msg an SVG filter is at most {_1} KB un filtre SVG ocupa com a màxim {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objecte no té cap efecte 3D (Extrudeix i bisella, Revoluciona, Infla o Gira) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` ha de ser un objecte que només contingui `mode`, amb el valor shaded o wireframe @msg its 3D effect builds no solid el seu efecte 3D no construeix cap sòlid diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 83662e4b5b..99a475d96d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6228,6 +6228,24 @@ mark-style Japanese Japonské @msg a 3D effect on a group's fill or stroke draws nothing 3D efekt na výplni nebo tahu skupiny nic nekreslí @msg a 3D effect on a group's fill or stroke draws nothing to export 3D efekt na výplni nebo tahu skupiny nekreslí nic k exportu @msg The 3D object is too complex to export 3D objekt je pro export příliš složitý +@msg the element needs an id, the filter's name prvek potřebuje id, název filtru +@msg an SVG filter's id is at most {MAX_NAME} characters id filtru SVG má nejvýše {MAX_NAME} znaků +@msg <{_1}> isn't an element of an SVG filter <{_1}> není prvkem filtru SVG +@msg an SVG filter has no event attributes such as {_1} filtr SVG nemá atributy událostí, jako je {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs obrázky filtru SVG jsou adresy data: ve formátu PNG, JPEG, GIF nebo WebP +@msg the SVG filter isn't valid XML: {e} filtr SVG není platné XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves prvku feTurbulence je nejvýše {MAX_OCTAVES} +@msg {what} is at most {max} {what} je nejvýše {max} +@msg feConvolveMatrix's order order prvku feConvolveMatrix +@msg feMorphology's radius radius prvku feMorphology +@msg a blur's stdDeviation stdDeviation rozostření +@msg the SVG filter has no primitives filtr SVG nemá žádná primitiva +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives filtr SVG má nejvýše {MAX_PRIMITIVES} primitiv +@msg the SVG filter is too large once its attributes are written out filtr SVG je po vypsání jeho atributů příliš velký +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all obrázky filtru SVG mají celkem nejvýše {MAX_IMAGE_PIXELS} pixelů +@msg the SVG filter can't be drawn: check its primitives and their inputs filtr SVG nelze vykreslit: zkontrolujte jeho primitiva a jejich vstupy +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep prvky filtru SVG jsou vnořeny nejvýše {MAX_DEPTH} úrovní hluboko +@msg an SVG filter is at most {_1} KB filtr SVG má nejvýše {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objekt nemá žádný 3D efekt (Vysunutí a zkosení, Rotační těleso, Nafouknutí ani Otočit) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musí být objekt obsahující pouze `mode` s hodnotou shaded nebo wireframe @msg its 3D effect builds no solid jeho 3D efekt nevytváří žádné těleso diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6a7c29cbce..85aed446b2 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -361,6 +361,25 @@ liquify-list-end {0}, {1} {0} og {1} @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere @msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg give one element angiv ét -element +@msg the element needs an id, the filter's name -elementet skal have et id, filterets navn +@msg an SVG filter's id is at most {MAX_NAME} characters et SVG-filters id er højst {MAX_NAME} tegn +@msg <{_1}> isn't an element of an SVG filter <{_1}> er ikke et element i et SVG-filter +@msg an SVG filter has no event attributes such as {_1} et SVG-filter har ingen hændelsesattributter som {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs et SVG-filters billeder er data:-URL'er i PNG, JPEG, GIF eller WebP +@msg the SVG filter isn't valid XML: {e} SVG-filteret er ikke gyldig XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves for feTurbulence er højst {MAX_OCTAVES} +@msg {what} is at most {max} {what} er højst {max} +@msg feConvolveMatrix's order order for feConvolveMatrix +@msg feMorphology's radius radius for feMorphology +@msg a blur's stdDeviation stdDeviation for en sløring +@msg the SVG filter has no primitives SVG-filteret har ingen filterprimitiver +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives et SVG-filter har højst {MAX_PRIMITIVES} filterprimitiver +@msg the SVG filter is too large once its attributes are written out SVG-filteret er for stort, når dets attributter er skrevet ud +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all et SVG-filters billeder har i alt højst {MAX_IMAGE_PIXELS} pixels +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG-filteret kan ikke tegnes: kontrollér dets filterprimitiver og deres input +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep et SVG-filters elementer er højst indlejret {MAX_DEPTH} niveauer dybt +@msg an SVG filter is at most {_1} KB et SVG-filter er højst {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` skal være et objekt, der kun indeholder `mode` med værdien shaded eller wireframe @msg its 3D effect builds no solid dens 3D-effekt danner intet legeme @@ -719,7 +738,7 @@ liquify-list-end {0}, {1} {0} og {1} Clear Recent Files Ryd seneste filer Show in Folder Vis i mappe Close Luk -@id file.close file.close +@id file.close Luk Close All Luk alle Save Gem Save As… Gem som… @@ -3187,7 +3206,7 @@ liquify-list-end {0}, {1} {0} og {1} Zig Zag… Zigzag… Pathfinder Pathfinder Add Foren -@id pathfinder.add pathfinder.add +@id pathfinder.add Foren Intersect Skæring Exclude Udeluk Subtract Træk fra diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1b1ec46863..091114c55d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5799,6 +5799,24 @@ lighting Light Licht @msg a 3D effect on a group's fill or stroke draws nothing ein 3D-Effekt auf der Fläche oder Kontur einer Gruppe zeichnet nichts @msg a 3D effect on a group's fill or stroke draws nothing to export ein 3D-Effekt auf der Fläche oder Kontur einer Gruppe zeichnet nichts, das exportiert werden kann @msg The 3D object is too complex to export Das 3D-Objekt ist zu komplex für den Export +@msg the element needs an id, the filter's name das -Element braucht eine id, den Namen des Filters +@msg an SVG filter's id is at most {MAX_NAME} characters die id eines SVG-Filters hat höchstens {MAX_NAME} Zeichen +@msg <{_1}> isn't an element of an SVG filter <{_1}> ist kein Element eines SVG-Filters +@msg an SVG filter has no event attributes such as {_1} ein SVG-Filter hat keine Ereignisattribute wie {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs die Bilder eines SVG-Filters sind data:-URLs im Format PNG, JPEG, GIF oder WebP +@msg the SVG filter isn't valid XML: {e} der SVG-Filter ist kein gültiges XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves von feTurbulence ist höchstens {MAX_OCTAVES} +@msg {what} is at most {max} {what} ist höchstens {max} +@msg feConvolveMatrix's order order von feConvolveMatrix +@msg feMorphology's radius radius von feMorphology +@msg a blur's stdDeviation stdDeviation einer Weichzeichnung +@msg the SVG filter has no primitives der SVG-Filter hat keine Filterprimitive +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives ein SVG-Filter hat höchstens {MAX_PRIMITIVES} Filterprimitive +@msg the SVG filter is too large once its attributes are written out der SVG-Filter ist zu groß, sobald seine Attribute ausgeschrieben sind +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all die Bilder eines SVG-Filters haben insgesamt höchstens {MAX_IMAGE_PIXELS} Pixel +@msg the SVG filter can't be drawn: check its primitives and their inputs der SVG-Filter kann nicht gezeichnet werden: Prüfen Sie seine Filterprimitive und deren Eingaben +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep die Elemente eines SVG-Filters sind höchstens {MAX_DEPTH} Ebenen tief verschachtelt +@msg an SVG filter is at most {_1} KB ein SVG-Filter ist höchstens {_1} KB groß @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) das Objekt hat keinen 3D-Effekt (Extrudieren und abgeflachte Kante, Kreiseln, Aufblasen oder Drehen) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` muss ein Objekt sein, das nur `mode` mit dem Wert shaded oder wireframe enthält @msg its 3D effect builds no solid sein 3D-Effekt erzeugt keinen Körper diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 618db0a6a8..560c5a91e3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2299,7 +2299,7 @@ font-technology Variable Μεταβλητές Vertical: Κατακόρυφα: View Προβολή W: Π: - Warp Παραμόρφωση + Warp Στρέβλωση Wave… Κύμα… Web Snap: Προσκόλληση στον ιστό: Weight Βάρος @@ -5615,6 +5615,25 @@ digits Malayalam Μαλαγιάλαμ @msg a 3D effect on a group's fill or stroke draws nothing ένα εφέ 3D στο γέμισμα ή στην πινελιά μιας ομάδας δεν σχεδιάζει τίποτα @msg a 3D effect on a group's fill or stroke draws nothing to export ένα εφέ 3D στο γέμισμα ή στην πινελιά μιας ομάδας δεν σχεδιάζει τίποτα για εξαγωγή @msg The 3D object is too complex to export Το αντικείμενο 3D είναι πολύ σύνθετο για εξαγωγή +@msg give one element δώστε ένα στοιχείο +@msg the element needs an id, the filter's name το στοιχείο χρειάζεται id, το όνομα του φίλτρου +@msg an SVG filter's id is at most {MAX_NAME} characters το id ενός φίλτρου SVG έχει το πολύ {MAX_NAME} χαρακτήρες +@msg <{_1}> isn't an element of an SVG filter το <{_1}> δεν είναι στοιχείο φίλτρου SVG +@msg an SVG filter has no event attributes such as {_1} ένα φίλτρο SVG δεν έχει χαρακτηριστικά συμβάντων όπως το {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs οι εικόνες ενός φίλτρου SVG είναι διευθύνσεις data: PNG, JPEG, GIF ή WebP +@msg the SVG filter isn't valid XML: {e} το φίλτρο SVG δεν είναι έγκυρη XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} το numOctaves του feTurbulence είναι το πολύ {MAX_OCTAVES} +@msg {what} is at most {max} {what}: το πολύ {max} +@msg feConvolveMatrix's order order του feConvolveMatrix +@msg feMorphology's radius radius του feMorphology +@msg a blur's stdDeviation stdDeviation ενός θολώματος +@msg the SVG filter has no primitives το φίλτρο SVG δεν έχει πρωτογενή στοιχεία +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives ένα φίλτρο SVG έχει το πολύ {MAX_PRIMITIVES} πρωτογενή στοιχεία +@msg the SVG filter is too large once its attributes are written out το φίλτρο SVG είναι πολύ μεγάλο όταν γραφτούν τα χαρακτηριστικά του +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all οι εικόνες ενός φίλτρου SVG έχουν συνολικά το πολύ {MAX_IMAGE_PIXELS} εικονοστοιχεία +@msg the SVG filter can't be drawn: check its primitives and their inputs το φίλτρο SVG δεν μπορεί να σχεδιαστεί: ελέγξτε τα πρωτογενή στοιχεία του και τις εισόδους τους +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep τα στοιχεία ενός φίλτρου SVG εμφωλεύονται σε βάθος το πολύ {MAX_DEPTH} επιπέδων +@msg an SVG filter is at most {_1} KB ένα φίλτρο SVG είναι το πολύ {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) το αντικείμενο δεν έχει εφέ 3D (Εξώθηση και λοξότμηση, Περιστροφή γύρω από άξονα, Φούσκωμα ή Περιστροφή) @msg `render` must be an object holding only `mode`, set to shaded or wireframe το `render` πρέπει να είναι αντικείμενο που περιέχει μόνο `mode`, με τιμή shaded ή wireframe @msg its 3D effect builds no solid το εφέ 3D του δεν δημιουργεί στερεό diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3cf461791e..ed20179e82 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6194,6 +6194,25 @@ mark-style Japanese Japonesas @msg a 3D effect on a group's fill or stroke draws nothing un efecto 3D en el relleno o el trazo de un grupo no dibuja nada @msg a 3D effect on a group's fill or stroke draws nothing to export un efecto 3D en el relleno o el trazo de un grupo no dibuja nada que exportar @msg The 3D object is too complex to export El objeto 3D es demasiado complejo para exportarlo +@msg give one element indique un elemento +@msg the element needs an id, the filter's name el elemento necesita un id, el nombre del filtro +@msg an SVG filter's id is at most {MAX_NAME} characters el id de un filtro SVG tiene como máximo {MAX_NAME} caracteres +@msg <{_1}> isn't an element of an SVG filter <{_1}> no es un elemento de un filtro SVG +@msg an SVG filter has no event attributes such as {_1} un filtro SVG no tiene atributos de evento como {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs las imágenes de un filtro SVG son URL data: en PNG, JPEG, GIF o WebP +@msg the SVG filter isn't valid XML: {e} el filtro SVG no es XML válido: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves de feTurbulence es como máximo {MAX_OCTAVES} +@msg {what} is at most {max} {what} es como máximo {max} +@msg feConvolveMatrix's order order de feConvolveMatrix +@msg feMorphology's radius radius de feMorphology +@msg a blur's stdDeviation stdDeviation de un desenfoque +@msg the SVG filter has no primitives el filtro SVG no tiene primitivas +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives un filtro SVG tiene como máximo {MAX_PRIMITIVES} primitivas +@msg the SVG filter is too large once its attributes are written out el filtro SVG es demasiado grande una vez escritos sus atributos +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all las imágenes de un filtro SVG tienen como máximo {MAX_IMAGE_PIXELS} píxeles en total +@msg the SVG filter can't be drawn: check its primitives and their inputs el filtro SVG no se puede dibujar: compruebe sus primitivas y sus entradas +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep los elementos de un filtro SVG se anidan como máximo {MAX_DEPTH} niveles +@msg an SVG filter is at most {_1} KB un filtro SVG ocupa como máximo {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) el objeto no tiene ningún efecto 3D (Extrusión y biselado, Revolución, Inflar o Rotar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` debe ser un objeto que solo contenga `mode`, con el valor shaded o wireframe @msg its 3D effect builds no solid su efecto 3D no construye ningún sólido diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0b1e3c881b..f0b4039c83 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6136,6 +6136,25 @@ mark-style Japanese Japanilainen @msg a 3D effect on a group's fill or stroke draws nothing ryhmän täytön tai viivan 3D-tehoste ei piirrä mitään @msg a 3D effect on a group's fill or stroke draws nothing to export ryhmän täytön tai viivan 3D-tehoste ei piirrä mitään vietävää @msg The 3D object is too complex to export 3D-objekti on liian monimutkainen vietäväksi +@msg give one element anna yksi -elementti +@msg the element needs an id, the filter's name -elementti tarvitsee id:n, suotimen nimen +@msg an SVG filter's id is at most {MAX_NAME} characters SVG-suotimen id on enintään {MAX_NAME} merkkiä +@msg <{_1}> isn't an element of an SVG filter <{_1}> ei ole SVG-suotimen elementti +@msg an SVG filter has no event attributes such as {_1} SVG-suotimessa ei ole tapahtumamääritteitä, kuten {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG-suotimen kuvat ovat PNG-, JPEG-, GIF- tai WebP-muotoisia data:-URL-osoitteita +@msg the SVG filter isn't valid XML: {e} SVG-suodin ei ole kelvollista XML:ää: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulencen numOctaves on enintään {MAX_OCTAVES} +@msg {what} is at most {max} {what} on enintään {max} +@msg feConvolveMatrix's order feConvolveMatrixin order +@msg feMorphology's radius feMorphologyn radius +@msg a blur's stdDeviation sumennuksen stdDeviation +@msg the SVG filter has no primitives SVG-suotimessa ei ole primitiivejä +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG-suotimessa on enintään {MAX_PRIMITIVES} primitiiviä +@msg the SVG filter is too large once its attributes are written out SVG-suodin on liian suuri, kun sen määritteet kirjoitetaan auki +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG-suotimen kuvissa on yhteensä enintään {MAX_IMAGE_PIXELS} pikseliä +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG-suodinta ei voi piirtää: tarkista sen primitiivit ja niiden syötteet +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG-suotimen elementit ovat sisäkkäin enintään {MAX_DEPTH} tason syvyydellä +@msg an SVG filter is at most {_1} KB SVG-suodin on enintään {_1} kt @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektilla ei ole 3D-tehostetta (Pursota ja viistä, Pyöräytä, Täytä ilmalla tai Kierrä) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` on oltava objekti, jossa on vain `mode` arvolla shaded tai wireframe @msg its 3D effect builds no solid sen 3D-tehoste ei muodosta kappaletta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b8667775fa..06a686c9ce 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5575,7 +5575,7 @@ effect Soft Doux On Both Sides Des deux côtés Short Courte Full Width Toute la largeur - Distort Déformation + Distort Distorsion Diffuse Glow… Lueur diffuse… Glass… Verre… Ocean Ripple… Océan… @@ -5792,6 +5792,24 @@ lighting Light Lumière @msg Revolve requires a shape with at least two anchors Révolution nécessite une forme comportant au moins deux points d’ancrage @msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} sur un groupe nécessite des tracés, tracés transparents, textes, groupes, groupes de découpe, dégradés de formes et occurrences de symbole : libérez ou développez d’abord ces éléments : {what}. @msg {label} on a group takes at most {MAX_MEMBERS} objects {label} sur un groupe accepte au plus {MAX_MEMBERS} objets +@msg the element needs an id, the filter's name l’élément doit avoir un id, le nom du filtre +@msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG compte au plus {MAX_NAME} caractères +@msg <{_1}> isn't an element of an SVG filter <{_1}> n’est pas un élément de filtre SVG +@msg an SVG filter has no event attributes such as {_1} un filtre SVG n’a pas d’attributs d’événement tels que {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs les images d’un filtre SVG sont des URL data: PNG, JPEG, GIF ou WebP +@msg the SVG filter isn't valid XML: {e} le filtre SVG n’est pas du XML valide : {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves de feTurbulence vaut au plus {MAX_OCTAVES} +@msg {what} is at most {max} {what} vaut au plus {max} +@msg feConvolveMatrix's order order de feConvolveMatrix +@msg feMorphology's radius radius de feMorphology +@msg a blur's stdDeviation stdDeviation d’un flou +@msg the SVG filter has no primitives le filtre SVG n’a aucune primitive +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives un filtre SVG a au plus {MAX_PRIMITIVES} primitives +@msg the SVG filter is too large once its attributes are written out le filtre SVG est trop volumineux une fois ses attributs écrits +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all les images d’un filtre SVG comptent au plus {MAX_IMAGE_PIXELS} pixels au total +@msg the SVG filter can't be drawn: check its primitives and their inputs le filtre SVG ne peut pas être dessiné : vérifiez ses primitives et leurs entrées +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep les éléments d’un filtre SVG s’imbriquent sur au plus {MAX_DEPTH} niveaux +@msg an SVG filter is at most {_1} KB un filtre SVG fait au plus {_1} Ko @msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke Un effet 3D sur un groupe ou un calque s’applique au groupe lui-même, pas à son fond ni à son contour @msg a 3D effect on a group's fill or stroke draws nothing un effet 3D sur le fond ou le contour d’un groupe ne dessine rien @msg a 3D effect on a group's fill or stroke draws nothing to export un effet 3D sur le fond ou le contour d’un groupe ne dessine rien à exporter diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 385fccc138..9bd0977cb5 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -330,7 +330,7 @@ Attach Objects on Path પાથ પર ઑબ્જેક્ટ જોડો Attach to Active Plane સક્રિય સમતલ પર જોડો Attribute: ગુણધર્મ: - Attributes ગુણધર્મો + Attributes એટ્રિબ્યુટ્સ Author Title: લેખકનું શીર્ષક: Author: લેખક: Auto ઑટો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e332f6be32..b977422495 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8316,6 +8316,25 @@ liquify-list-end {0}, {1} {0} और {1} @msg a 3D effect on a group's fill or stroke draws nothing ग्रुप के फ़िल या स्ट्रोक पर 3D इफ़ेक्ट कुछ नहीं बनाता @msg a 3D effect on a group's fill or stroke draws nothing to export ग्रुप के फ़िल या स्ट्रोक पर 3D इफ़ेक्ट एक्सपोर्ट करने लायक कुछ नहीं बनाता @msg The 3D object is too complex to export 3D ऑब्जेक्ट एक्सपोर्ट करने के लिए बहुत जटिल है +@msg give one element एक एलिमेंट दें +@msg the element needs an id, the filter's name एलिमेंट को एक id चाहिए, जो फ़िल्टर का नाम है +@msg an SVG filter's id is at most {MAX_NAME} characters SVG फ़िल्टर की id अधिकतम {MAX_NAME} वर्णों की होती है +@msg <{_1}> isn't an element of an SVG filter <{_1}> SVG फ़िल्टर का एलिमेंट नहीं है +@msg an SVG filter has no event attributes such as {_1} SVG फ़िल्टर में {_1} जैसे इवेंट एट्रिब्यूट नहीं होते +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG फ़िल्टर की इमेज PNG, JPEG, GIF या WebP data: URL होती हैं +@msg the SVG filter isn't valid XML: {e} SVG फ़िल्टर मान्य XML नहीं है: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence का numOctaves अधिकतम {MAX_OCTAVES} होता है +@msg {what} is at most {max} {what} अधिकतम {max} होता है +@msg feConvolveMatrix's order feConvolveMatrix का order +@msg feMorphology's radius feMorphology का radius +@msg a blur's stdDeviation ब्लर का stdDeviation +@msg the SVG filter has no primitives SVG फ़िल्टर में कोई प्रिमिटिव नहीं है +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG फ़िल्टर में अधिकतम {MAX_PRIMITIVES} प्रिमिटिव होते हैं +@msg the SVG filter is too large once its attributes are written out एट्रिब्यूट लिखे जाने के बाद SVG फ़िल्टर बहुत बड़ा हो जाता है +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG फ़िल्टर की इमेज में कुल मिलाकर अधिकतम {MAX_IMAGE_PIXELS} पिक्सेल होते हैं +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG फ़िल्टर बनाया नहीं जा सकता: उसके प्रिमिटिव और उनके इनपुट जाँचें +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG फ़िल्टर के एलिमेंट अधिकतम {MAX_DEPTH} स्तर तक नेस्ट होते हैं +@msg an SVG filter is at most {_1} KB SVG फ़िल्टर अधिकतम {_1} KB का होता है @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ऑब्जेक्ट पर कोई 3D इफ़ेक्ट नहीं है (एक्सट्रूडेड और बेवेल, रिवॉल्व, फुलाएँ या घुमाव) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` केवल `mode` वाला ऑब्जेक्ट होना चाहिए, जिसका मान shaded या wireframe हो @msg its 3D effect builds no solid इसका 3D इफ़ेक्ट कोई ठोस नहीं बनाता diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e4452cb211..42a4a81a6b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6212,6 +6212,24 @@ liquify-list-end {0}, {1} {0} és {1} @msg a 3D effect on a group's fill or stroke draws nothing a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmit @msg a 3D effect on a group's fill or stroke draws nothing to export a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmi exportálhatót @msg The 3D object is too complex to export A 3D objektum túl összetett az exportáláshoz +@msg the element needs an id, the filter's name a elemnek id kell, a szűrő neve +@msg an SVG filter's id is at most {MAX_NAME} characters egy SVG-szűrő id-je legfeljebb {MAX_NAME} karakter +@msg <{_1}> isn't an element of an SVG filter a(z) <{_1}> nem SVG-szűrő eleme +@msg an SVG filter has no event attributes such as {_1} egy SVG-szűrőnek nincsenek eseményattribútumai, például {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs egy SVG-szűrő képei PNG, JPEG, GIF vagy WebP formátumú data: URL-ek +@msg the SVG filter isn't valid XML: {e} az SVG-szűrő nem érvényes XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} a feTurbulence numOctaves értéke legfeljebb {MAX_OCTAVES} +@msg {what} is at most {max} {what} legfeljebb {max} +@msg feConvolveMatrix's order a feConvolveMatrix order értéke +@msg feMorphology's radius a feMorphology radius értéke +@msg a blur's stdDeviation egy elmosás stdDeviation értéke +@msg the SVG filter has no primitives az SVG-szűrőnek nincsenek primitívjei +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives egy SVG-szűrőnek legfeljebb {MAX_PRIMITIVES} primitívje van +@msg the SVG filter is too large once its attributes are written out az SVG-szűrő túl nagy, miután az attribútumai ki vannak írva +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all egy SVG-szűrő képei összesen legfeljebb {MAX_IMAGE_PIXELS} képpontosak +@msg the SVG filter can't be drawn: check its primitives and their inputs az SVG-szűrő nem rajzolható meg: ellenőrizze a primitívjeit és azok bemeneteit +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep egy SVG-szűrő elemei legfeljebb {MAX_DEPTH} szint mélyen ágyazhatók egymásba +@msg an SVG filter is at most {_1} KB egy SVG-szűrő legfeljebb {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) az objektumnak nincs 3D effektusa (Kihúzás és élletörés, Forgatás tengely körül, Felfújás vagy Elforgatás) @msg `render` must be an object holding only `mode`, set to shaded or wireframe a `render` csak `mode` mezőt tartalmazó objektum lehet, shaded vagy wireframe értékkel @msg its 3D effect builds no solid a 3D effektusa nem hoz létre testet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 37ea827f3c..ebd1697020 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -34,7 +34,7 @@ Clear Recent Files Kosongkan berkas terbaru Show in Folder Tampilkan di folder Close Tutup -@id file.close berkas.tutup +@id file.close Tutup Close All Tutup semua Save Simpan Save As… Simpan sebagai… @@ -513,7 +513,7 @@ Zig Zag… Zig Zag… Pathfinder Pathfinder Add Tambah -@id pathfinder.add pathfinder.tambah +@id pathfinder.add Satukan Intersect Iris Exclude Kecualikan Subtract Kurangi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7005d218f7..147e5bfe35 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5843,6 +5843,24 @@ lighting Light Luce @msg a 3D effect on a group's fill or stroke draws nothing un effetto 3D sul riempimento o sulla traccia di un gruppo non disegna nulla @msg a 3D effect on a group's fill or stroke draws nothing to export un effetto 3D sul riempimento o sulla traccia di un gruppo non disegna nulla da esportare @msg The 3D object is too complex to export L'oggetto 3D è troppo complesso per essere esportato +@msg the element needs an id, the filter's name l'elemento richiede un id, il nome del filtro +@msg an SVG filter's id is at most {MAX_NAME} characters l'id di un filtro SVG ha al massimo {MAX_NAME} caratteri +@msg <{_1}> isn't an element of an SVG filter <{_1}> non è un elemento di un filtro SVG +@msg an SVG filter has no event attributes such as {_1} un filtro SVG non ha attributi di evento come {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs le immagini di un filtro SVG sono URL data: PNG, JPEG, GIF o WebP +@msg the SVG filter isn't valid XML: {e} il filtro SVG non è XML valido: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves di feTurbulence è al massimo {MAX_OCTAVES} +@msg {what} is at most {max} {what} è al massimo {max} +@msg feConvolveMatrix's order order di feConvolveMatrix +@msg feMorphology's radius radius di feMorphology +@msg a blur's stdDeviation stdDeviation di una sfocatura +@msg the SVG filter has no primitives il filtro SVG non ha primitive +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives un filtro SVG ha al massimo {MAX_PRIMITIVES} primitive +@msg the SVG filter is too large once its attributes are written out il filtro SVG è troppo grande una volta scritti i suoi attributi +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all le immagini di un filtro SVG hanno al massimo {MAX_IMAGE_PIXELS} pixel in tutto +@msg the SVG filter can't be drawn: check its primitives and their inputs impossibile disegnare il filtro SVG: controlla le sue primitive e i relativi input +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep gli elementi di un filtro SVG si annidano al massimo per {MAX_DEPTH} livelli +@msg an SVG filter is at most {_1} KB un filtro SVG occupa al massimo {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l'oggetto non ha alcun effetto 3D (Estrusione e smusso, Rivoluzione, Gonfia o Ruota) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` deve essere un oggetto che contiene solo `mode`, con valore shaded o wireframe @msg its 3D effect builds no solid il suo effetto 3D non costruisce alcun solido diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9b403f103c..6db09e8cfe 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5886,6 +5886,24 @@ lighting Light ライト @msg a 3D effect on a group's fill or stroke draws nothing グループの塗りまたは線にある 3D 効果は何も描画しません @msg a 3D effect on a group's fill or stroke draws nothing to export グループの塗りまたは線にある 3D 効果には書き出せる描画がありません @msg The 3D object is too complex to export 3D オブジェクトが複雑すぎるため書き出せません +@msg the element needs an id, the filter's name 要素には id (フィルターの名前) が必要です +@msg an SVG filter's id is at most {MAX_NAME} characters SVG フィルターの id は {MAX_NAME} 文字までです +@msg <{_1}> isn't an element of an SVG filter <{_1}> は SVG フィルターの要素ではありません +@msg an SVG filter has no event attributes such as {_1} SVG フィルターには {_1} などのイベント属性は使えません +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG フィルターの画像は PNG、JPEG、GIF、WebP の data: URL に限ります +@msg the SVG filter isn't valid XML: {e} SVG フィルターが有効な XML ではありません: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence の numOctaves は {MAX_OCTAVES} までです +@msg {what} is at most {max} {what} は {max} までです +@msg feConvolveMatrix's order feConvolveMatrix の order +@msg feMorphology's radius feMorphology の radius +@msg a blur's stdDeviation ぼかしの stdDeviation +@msg the SVG filter has no primitives SVG フィルターにプリミティブがありません +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG フィルターのプリミティブは {MAX_PRIMITIVES} 個までです +@msg the SVG filter is too large once its attributes are written out 属性を書き出すと SVG フィルターが大きくなりすぎます +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG フィルターの画像は合計 {MAX_IMAGE_PIXELS} ピクセルまでです +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG フィルターを描画できません: プリミティブとその入力を確認してください +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG フィルターの要素の入れ子は {MAX_DEPTH} 階層までです +@msg an SVG filter is at most {_1} KB SVG フィルターは {_1} KB までです @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) オブジェクトに 3D 効果 (押し出しとベベル、回転体、膨張、回転) がありません @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` は `mode` だけを持ち、その値が shaded または wireframe のオブジェクトにしてください @msg its 3D effect builds no solid 3D 効果からソリッドが作成されません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a069c9bac6..858cb6f296 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7541,6 +7541,9 @@ font-technology Variable ცვლადი @msg a 3D effect on a group's fill or stroke draws nothing ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი არაფერს ხატავს @msg a 3D effect on a group's fill or stroke draws nothing to export ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი ექსპორტისთვის არაფერს ხატავს @msg The 3D object is too complex to export 3D ობიექტი ზედმეტად რთულია ექსპორტისთვის +@msg feConvolveMatrix's order feConvolveMatrix-ის order +@msg feMorphology's radius feMorphology-ის radius +@msg a blur's stdDeviation დაბინდვის stdDeviation @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ობიექტს არ აქვს 3D ეფექტი (ამოწევა და წაკვეთა, ბრუნვა, გაბერვა ან შემობრუნება) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` უნდა იყოს ობიექტი, რომელიც შეიცავს მხოლოდ `mode`-ს, მნიშვნელობით shaded ან wireframe @msg its 3D effect builds no solid მისი 3D ეფექტი სხეულს არ ქმნის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e2de2a8d46..fa8686588f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -621,7 +621,7 @@ digits Malayalam 말라얄람어 Feather… 페더… SVG Filters SVG 필터 Apply SVG Filter… SVG 필터 적용… - Warp 왜곡 + Warp 뒤틀기 Arc… 호… Arc Lower… 아래쪽 호… Arc Upper… 위쪽 호… @@ -768,7 +768,7 @@ digits Malayalam 말라얄람어 Keep Tools Beside the Canvas 캔버스 옆에 도구 배치 Actions 액션 Asset Export 에셋 내보내기 - Attributes 속성 + Attributes 특성 Brushes 브러시 Color 색상 Color Guide 색상 가이드 @@ -5805,6 +5805,24 @@ lighting Light 광원 @msg a 3D effect on a group's fill or stroke draws nothing 그룹의 칠이나 획에 있는 3D 효과는 아무것도 그리지 않습니다 @msg a 3D effect on a group's fill or stroke draws nothing to export 그룹의 칠이나 획에 있는 3D 효과는 내보낼 것을 그리지 않습니다 @msg The 3D object is too complex to export 3D 개체가 너무 복잡하여 내보낼 수 없습니다 +@msg the element needs an id, the filter's name 요소에는 필터 이름인 id가 필요합니다 +@msg an SVG filter's id is at most {MAX_NAME} characters SVG 필터의 id는 최대 {MAX_NAME}자입니다 +@msg <{_1}> isn't an element of an SVG filter <{_1}>은(는) SVG 필터의 요소가 아닙니다 +@msg an SVG filter has no event attributes such as {_1} SVG 필터에는 {_1} 같은 이벤트 속성이 없습니다 +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG 필터의 이미지는 PNG, JPEG, GIF 또는 WebP data: URL입니다 +@msg the SVG filter isn't valid XML: {e} SVG 필터가 올바른 XML이 아닙니다: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence의 numOctaves는 최대 {MAX_OCTAVES}입니다 +@msg {what} is at most {max} {what}은(는) 최대 {max}입니다 +@msg feConvolveMatrix's order feConvolveMatrix의 order +@msg feMorphology's radius feMorphology의 radius +@msg a blur's stdDeviation 흐림 효과의 stdDeviation +@msg the SVG filter has no primitives SVG 필터에 프리미티브가 없습니다 +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG 필터의 프리미티브는 최대 {MAX_PRIMITIVES}개입니다 +@msg the SVG filter is too large once its attributes are written out 속성을 모두 쓰면 SVG 필터가 너무 커집니다 +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG 필터의 이미지는 모두 합쳐 최대 {MAX_IMAGE_PIXELS}픽셀입니다 +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG 필터를 그릴 수 없습니다: 프리미티브와 그 입력을 확인하세요 +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG 필터의 요소는 최대 {MAX_DEPTH}단계까지 중첩됩니다 +@msg an SVG filter is at most {_1} KB SVG 필터는 최대 {_1}KB입니다 @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 개체에 3D 효과(돌출 및 경사, 회전체, 부풀리기 또는 회전)가 없습니다 @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`는 값이 shaded 또는 wireframe인 `mode`만 있는 객체여야 합니다 @msg its 3D effect builds no solid 3D 효과가 입체를 만들지 않습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index aaa159876e..88c247c2f1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -588,7 +588,7 @@ liquify-list-end {0}, {1} {0} en {1} Clear Recent Files Recente bestanden wissen Show in Folder Tonen in map Close Sluiten -@id file.close file.close +@id file.close Sluiten Close All Alles sluiten Save Opslaan Save As… Opslaan als… @@ -1081,7 +1081,7 @@ liquify-list-end {0}, {1} {0} en {1} Zig Zag… Zigzag… Pathfinder Padvinder Add Toevoegen -@id pathfinder.add pathfinder.add +@id pathfinder.add Verenigen Intersect Doorsnede Exclude Uitsluiten Subtract Aftrekken @@ -7985,6 +7985,24 @@ mark-style Japanese Japans @msg a 3D effect on a group's fill or stroke draws nothing een 3D-effect op de vulling of contour van een groep tekent niets @msg a 3D effect on a group's fill or stroke draws nothing to export een 3D-effect op de vulling of contour van een groep tekent niets om te exporteren @msg The 3D object is too complex to export Het 3D-object is te complex om te exporteren +@msg the element needs an id, the filter's name het -element heeft een id nodig, de naam van het filter +@msg an SVG filter's id is at most {MAX_NAME} characters de id van een SVG-filter is hoogstens {MAX_NAME} tekens lang +@msg <{_1}> isn't an element of an SVG filter <{_1}> is geen element van een SVG-filter +@msg an SVG filter has no event attributes such as {_1} een SVG-filter heeft geen gebeurtenisattributen zoals {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs de afbeeldingen van een SVG-filter zijn data:-URL's in PNG, JPEG, GIF of WebP +@msg the SVG filter isn't valid XML: {e} het SVG-filter is geen geldige XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves van feTurbulence is hoogstens {MAX_OCTAVES} +@msg {what} is at most {max} {what} is hoogstens {max} +@msg feConvolveMatrix's order order van feConvolveMatrix +@msg feMorphology's radius radius van feMorphology +@msg a blur's stdDeviation stdDeviation van een vervaging +@msg the SVG filter has no primitives het SVG-filter heeft geen primitieven +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives een SVG-filter heeft hoogstens {MAX_PRIMITIVES} primitieven +@msg the SVG filter is too large once its attributes are written out het SVG-filter is te groot zodra de attributen zijn uitgeschreven +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all de afbeeldingen van een SVG-filter hebben samen hoogstens {MAX_IMAGE_PIXELS} pixels +@msg the SVG filter can't be drawn: check its primitives and their inputs het SVG-filter kan niet worden getekend: controleer de primitieven en hun invoer +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep de elementen van een SVG-filter zijn hoogstens {MAX_DEPTH} niveaus diep genest +@msg an SVG filter is at most {_1} KB een SVG-filter is hoogstens {_1} kB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) het object heeft geen 3D-effect (Extruderen en afschuinen, Draaien, Opblazen of Roteren) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` moet een object zijn met alleen `mode`, ingesteld op shaded of wireframe @msg its 3D effect builds no solid het 3D-effect ervan maakt geen massief object diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6f7c6eb49a..4e36d0249a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6058,6 +6058,24 @@ mark-style Japanese Japońskie @msg a 3D effect on a group's fill or stroke draws nothing efekt 3D na wypełnieniu lub obrysie grupy niczego nie rysuje @msg a 3D effect on a group's fill or stroke draws nothing to export efekt 3D na wypełnieniu lub obrysie grupy nie rysuje niczego do eksportu @msg The 3D object is too complex to export Obiekt 3D jest zbyt złożony, aby go wyeksportować +@msg the element needs an id, the filter's name element wymaga id, czyli nazwy filtra +@msg an SVG filter's id is at most {MAX_NAME} characters id filtra SVG ma najwyżej {MAX_NAME} znaków +@msg <{_1}> isn't an element of an SVG filter <{_1}> nie jest elementem filtra SVG +@msg an SVG filter has no event attributes such as {_1} filtr SVG nie ma atrybutów zdarzeń, takich jak {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs obrazy filtra SVG to adresy data: PNG, JPEG, GIF lub WebP +@msg the SVG filter isn't valid XML: {e} filtr SVG nie jest poprawnym XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves elementu feTurbulence wynosi najwyżej {MAX_OCTAVES} +@msg {what} is at most {max} {what} wynosi najwyżej {max} +@msg feConvolveMatrix's order order elementu feConvolveMatrix +@msg feMorphology's radius radius elementu feMorphology +@msg a blur's stdDeviation stdDeviation rozmycia +@msg the SVG filter has no primitives filtr SVG nie ma prymitywów +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives filtr SVG ma najwyżej {MAX_PRIMITIVES} prymitywów +@msg the SVG filter is too large once its attributes are written out filtr SVG jest zbyt duży po zapisaniu jego atrybutów +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all obrazy filtra SVG mają łącznie najwyżej {MAX_IMAGE_PIXELS} pikseli +@msg the SVG filter can't be drawn: check its primitives and their inputs nie można narysować filtra SVG: sprawdź jego prymitywy i ich wejścia +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep elementy filtra SVG zagnieżdżają się najwyżej na {MAX_DEPTH} poziomów +@msg an SVG filter is at most {_1} KB filtr SVG ma najwyżej {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) obiekt nie ma efektu 3D (Wyciągnięcie i fazowanie, Obrót, Nadmuchanie ani Obróć) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musi być obiektem zawierającym tylko `mode` o wartości shaded lub wireframe @msg its 3D effect builds no solid jego efekt 3D nie tworzy żadnej bryły diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4138d050c8..b5dc29791e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -227,7 +227,7 @@ antiAlias Sharp Nítido Arc Lower… Arco Inferior… Arc Tool Ferramenta Arco Arc Upper… Arco Superior… - Arch… Arco… + Arch… Abóbada… Arc… Arco… Area / Path Type Texto de Área / Caminho Area Graph Tool Ferramenta Gráfico de Área @@ -1335,7 +1335,7 @@ antiAlias Sharp Nítido Guides & Grid Guias e Grade H Spacing: Espaçamento H: H: H: - Hair Space Espaço Fino + Hair Space Espaço Ultrafino Hand Tool Ferramenta Mão Hand-Drawn Desenhado à Mão Painted and Sketched Pintado e Esboçado @@ -3229,7 +3229,7 @@ digits Malayalam Malaiala Trim mark weight: Peso da marca de corte: True colour needs version 2004 or later: the nearest of 256 colours is written. A cor verdadeira requer a versão 2004 ou posterior: a cor mais próxima das 256 cores é escrita. Turn off Data Recovery for complex documents Desligar Recuperação de Dados para documentos complexos - Tweak… Torcer… + Tweak… Ajustar… Twirl Rate: Taxa de Redemoinho: Twirl Tool Ferramenta Redemoinho Twist… Torcer… @@ -3377,7 +3377,7 @@ digits Malayalam Malaiala Viewing Distance: Distância de Visualização: W: W: Warnings Avisos - Warp Distorcer + Warp Deformar Warp Options Opções de Distorção Warp Tool Ferramenta Distorcer Wave… Onda… @@ -6180,6 +6180,24 @@ mark-style Japanese Japonesas @msg a 3D effect on a group's fill or stroke draws nothing um efeito 3D no preenchimento ou traçado de um grupo não desenha nada @msg a 3D effect on a group's fill or stroke draws nothing to export um efeito 3D no preenchimento ou traçado de um grupo não desenha nada para exportar @msg The 3D object is too complex to export O objeto 3D é complexo demais para ser exportado +@msg the element needs an id, the filter's name o elemento precisa de um id, o nome do filtro +@msg an SVG filter's id is at most {MAX_NAME} characters o id de um filtro SVG tem no máximo {MAX_NAME} caracteres +@msg <{_1}> isn't an element of an SVG filter <{_1}> não é um elemento de filtro SVG +@msg an SVG filter has no event attributes such as {_1} um filtro SVG não tem atributos de evento como {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs as imagens de um filtro SVG são URLs data: em PNG, JPEG, GIF ou WebP +@msg the SVG filter isn't valid XML: {e} o filtro SVG não é um XML válido: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves de feTurbulence é no máximo {MAX_OCTAVES} +@msg {what} is at most {max} {what} é no máximo {max} +@msg feConvolveMatrix's order order de feConvolveMatrix +@msg feMorphology's radius radius de feMorphology +@msg a blur's stdDeviation stdDeviation de um desfoque +@msg the SVG filter has no primitives o filtro SVG não tem primitivas +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives um filtro SVG tem no máximo {MAX_PRIMITIVES} primitivas +@msg the SVG filter is too large once its attributes are written out o filtro SVG fica grande demais depois que seus atributos são escritos +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all as imagens de um filtro SVG têm no máximo {MAX_IMAGE_PIXELS} pixels no total +@msg the SVG filter can't be drawn: check its primitives and their inputs não é possível desenhar o filtro SVG: verifique suas primitivas e as entradas delas +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep os elementos de um filtro SVG se aninham em no máximo {MAX_DEPTH} níveis +@msg an SVG filter is at most {_1} KB um filtro SVG tem no máximo {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) o objeto não tem efeito 3D (Extrusão e Bisel, Revolver, Inflar ou Girar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` deve ser um objeto que contenha apenas `mode`, com o valor shaded ou wireframe @msg its 3D effect builds no solid seu efeito 3D não constrói nenhum sólido diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5f73b0dd78..92bf430f65 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2119,7 +2119,7 @@ file-filter Templates Шаблоны Medium Thumbnail View Средние миниатюры Medium Thumbnails Средние миниатюры Menu Dialog Диалоговое окно меню - Merge Объединить + Merge Слить Merge colors into one row Объединить цвета в одну строку New Row Новая строка Merge Graphic Styles Объединить графические стили @@ -5841,6 +5841,24 @@ lighting Light Свет @msg a 3D effect on a group's fill or stroke draws nothing 3D-эффект на заливке или обводке группы ничего не рисует @msg a 3D effect on a group's fill or stroke draws nothing to export 3D-эффект на заливке или обводке группы не рисует ничего для экспорта @msg The 3D object is too complex to export 3D-объект слишком сложен для экспорта +@msg the element needs an id, the filter's name элементу нужен id, имя фильтра +@msg an SVG filter's id is at most {MAX_NAME} characters id фильтра SVG содержит не более {MAX_NAME} символов +@msg <{_1}> isn't an element of an SVG filter <{_1}> не является элементом фильтра SVG +@msg an SVG filter has no event attributes such as {_1} у фильтра SVG нет атрибутов событий, таких как {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs изображения фильтра SVG задаются URL data: в формате PNG, JPEG, GIF или WebP +@msg the SVG filter isn't valid XML: {e} фильтр SVG не является допустимым XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves у feTurbulence не больше {MAX_OCTAVES} +@msg {what} is at most {max} {what}: не больше {max} +@msg feConvolveMatrix's order order у feConvolveMatrix +@msg feMorphology's radius radius у feMorphology +@msg a blur's stdDeviation stdDeviation размытия +@msg the SVG filter has no primitives у фильтра SVG нет примитивов +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives у фильтра SVG не более {MAX_PRIMITIVES} примитивов +@msg the SVG filter is too large once its attributes are written out фильтр SVG становится слишком большим после записи его атрибутов +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all изображения фильтра SVG содержат в сумме не более {MAX_IMAGE_PIXELS} пикселей +@msg the SVG filter can't be drawn: check its primitives and their inputs не удается нарисовать фильтр SVG: проверьте его примитивы и их входы +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep элементы фильтра SVG вкладываются не глубже {MAX_DEPTH} уровней +@msg an SVG filter is at most {_1} KB размер фильтра SVG не более {_1} КБ @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) у объекта нет 3D-эффекта (Выдавливание и фаска, Вращение, Надувание или Повернуть) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` должен быть объектом только с полем `mode` со значением shaded или wireframe @msg its 3D effect builds no solid его 3D-эффект не строит тела diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 769e5c7873..7e51593cca 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5501,7 +5501,7 @@ effect Soft Mjuk On Both Sides På båda sidor Short Kort Full Width Full bredd - Distort Förvräng + Distort Förvrängning Diffuse Glow… Diffus glöd… Glass… Glas… Ocean Ripple… Havskrusning… @@ -5717,6 +5717,25 @@ lighting Light Ljus @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en grupps fyllning eller linje ritar ingenting @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en grupps fyllning eller linje ritar ingenting att exportera @msg The 3D object is too complex to export 3D-objektet är för komplext för att exporteras +@msg give one element ange ett -element +@msg the element needs an id, the filter's name -elementet behöver ett id, filtrets namn +@msg an SVG filter's id is at most {MAX_NAME} characters ett SVG-filters id har högst {MAX_NAME} tecken +@msg <{_1}> isn't an element of an SVG filter <{_1}> är inte ett element i ett SVG-filter +@msg an SVG filter has no event attributes such as {_1} ett SVG-filter har inga händelseattribut som {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs ett SVG-filters bilder är data:-URL:er i PNG, JPEG, GIF eller WebP +@msg the SVG filter isn't valid XML: {e} SVG-filtret är inte giltig XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves för feTurbulence är högst {MAX_OCTAVES} +@msg {what} is at most {max} {what} är högst {max} +@msg feConvolveMatrix's order order för feConvolveMatrix +@msg feMorphology's radius radius för feMorphology +@msg a blur's stdDeviation stdDeviation för en oskärpa +@msg the SVG filter has no primitives SVG-filtret har inga primitiver +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives ett SVG-filter har högst {MAX_PRIMITIVES} primitiver +@msg the SVG filter is too large once its attributes are written out SVG-filtret blir för stort när dess attribut skrivs ut +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all ett SVG-filters bilder har högst {MAX_IMAGE_PIXELS} pixlar sammanlagt +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG-filtret kan inte ritas: kontrollera dess primitiver och deras indata +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep ett SVG-filters element kapslas högst {MAX_DEPTH} nivåer djupt +@msg an SVG filter is at most {_1} KB ett SVG-filter är högst {_1} KB @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Extrudera och fasa, Rotera runt axel, Blås upp eller Rotera) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` måste vara ett objekt som bara innehåller `mode`, med värdet shaded eller wireframe @msg its 3D effect builds no solid dess 3D-effekt bygger ingen solid diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a540fdc463..ed4b44b0da 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1724,6 +1724,92 @@ fn menu_labels() -> Vec<(&'static str, &'static str, serde_json::Value)> { labels } +/// The effect an Effect menu item (`effect.apply` or `effect.dialog`) runs. +fn menu_item_effect<'a>(id: &str, p: &'a serde_json::Value) -> Option<&'a str> { + p.get("effect").and_then(serde_json::Value::as_str).filter(|_| matches!(id, "effect.apply" | "effect.dialog")) +} + +/// The label a menu item shows in `lang`, as the menus resolve it: an Effect menu item by its +/// effect's `@id` row when the catalog has one, any other command by its id's row or its English +/// label, and a submenu or an unbuilt item by its English label. +fn shown_menu_label(lang: Lang, item: &crate::menus::Item) -> Option<&'static str> { + use crate::menus::Item; + match item { + Item::Cmd(l, id, p) => { + let by_effect = menu_item_effect(id, p).map(|e| tr_id(lang, e, "")).filter(|s| !s.is_empty()); + Some(by_effect.unwrap_or_else(|| tr_id(lang, id, l))) + } + Item::Todo(l, _) | Item::Sub(l, _) => Some(tr(lang, l)), + Item::Header(_) | Item::Sep => None, + } +} + +/// Items side by side in a menu show different labels in every language, so each can be told +/// from the others. Items with the same English label (the slots of a recent-files list) are +/// alike in every language. +#[test] +fn menu_items_side_by_side_have_different_labels() { + use crate::menus::Item; + fn walk(lang: Lang, path: &str, items: &[Item], out: &mut Vec) { + let mut seen: std::collections::BTreeMap<&str, (&str, &str)> = std::collections::BTreeMap::new(); + for item in items { + let Some(shown) = shown_menu_label(lang, item) else { continue }; + let (english, what) = match item { + Item::Cmd(l, id, p) => (*l, menu_item_effect(id, p).unwrap_or(id)), + Item::Todo(l, _) | Item::Sub(l, _) => (*l, "submenu or unbuilt item"), + Item::Header(_) | Item::Sep => continue, + }; + match seen.get(shown) { + Some(&(other, other_what)) if other != english => { + out.push(format!("{}: {path}: {other:?} ({other_what}) and {english:?} ({what}) both show {shown:?}", lang.0.code)); + } + Some(_) => {} + None => { + seen.insert(shown, (english, what)); + } + } + if let Item::Sub(l, children) = item { + walk(lang, &format!("{path} › {l}"), children, out); + } + } + } + let tree = crate::menus::menu_tree(); + let mut same = vec![]; + for l in &LANGUAGES { + for (title, items) in &tree { + walk(Lang(l), title, items, &mut same); + } + } + assert!(same.is_empty(), "{} pairs of menu items look alike:\n{}", same.len(), same.join("\n")); +} + +/// Menu items show words, never the command or effect id their catalog row is keyed by. +#[test] +fn menu_items_never_show_an_id() { + fn walk(lang: Lang, items: &[crate::menus::Item], out: &mut Vec) { + for item in items { + if let crate::menus::Item::Cmd(l, id, p) = item { + let key = menu_item_effect(id, p).unwrap_or(id); + let shown = shown_menu_label(lang, item).unwrap_or_default(); + if !command_ids(shown).is_empty() && command_ids(l).is_empty() { + out.push(format!("{}: {l:?} ({key}) shows {shown:?}", lang.0.code)); + } + } + if let crate::menus::Item::Sub(_, children) = item { + walk(lang, children, out); + } + } + } + let tree = crate::menus::menu_tree(); + let mut ids = vec![]; + for l in &LANGUAGES { + for (_, items) in &tree { + walk(Lang(l), items, &mut ids); + } + } + assert!(ids.is_empty(), "{} menu items show an id:\n{}", ids.len(), ids.join("\n")); +} + /// The labels toggling items switch to ("Show Guides" once guides are hidden…), from a document /// with every toggle flipped. fn toggled_labels() -> Vec { @@ -3004,6 +3090,98 @@ fn three_d_refusals_translate_with_their_values() { assert_eq!(message(de(), &errors[1].0), "ungültige Parameter für `effect.apply`: Licht: intensity muss eine Zahl von 0 bis 100 sein"); } +/// The values SVG filter refusals put in `{what}` that are messages of their own: the attributes +/// over their limit, named with their element. `kernelUnitLength` is an attribute's name as written. +const SVG_FILTER_PARTS: &[&str] = &["feConvolveMatrix's order", "feMorphology's radius", "a blur's stdDeviation"]; + +/// The SVG filter check's refusals as catalog templates: the messages of `svg_filter.rs` that +/// [`source_messages`] finds, the XML errors its `map_err` closures make included. +fn svg_filter_refusals() -> std::collections::BTreeSet { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../effects/src/svg_filter.rs"); + let text = std::fs::read_to_string(path).expect("the SVG filter source"); + let code = without_test_module(&text); + let mut consts = std::collections::BTreeMap::new(); + for (name, value) in str_consts(code) { + consts.entry(name).or_insert_with(Vec::new).push(value); + } + source_messages(code, &[], &consts).into_iter().collect() +} + +/// The SVG filter check's refusals, and the attributes they name, have an `@msg` row in every +/// complete-message catalog. +#[test] +fn svg_filter_refusals_are_translated_in_every_complete_catalog() { + let refusals = svg_filter_refusals(); + assert!(refusals.len() >= 16, "scan found only {} SVG filter refusals: {refusals:?}", refusals.len()); + for m in [ + "the SVG filter isn't valid XML: {e}", + "an SVG filter's id is at most {MAX_NAME} characters", + "<{_1}> isn't an element of an SVG filter", + "{what} is at most {max}", + "an SVG filter is at most {_1} KB", + ] { + assert!(refusals.contains(m), "the scan reads map_err closures and format! arguments: {m}"); + } + let mut missing = vec![]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: std::collections::BTreeSet<&str> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, _)| src.as_str()).collect(); + let parts = SVG_FILTER_PARTS.iter().map(|p| p.to_string()); + missing.extend(refusals.iter().cloned().chain(parts).filter(|m| !rows.contains(m.as_str())).map(|m| format!("{code}: {m}"))); + } + assert!(missing.is_empty(), "{} SVG filter messages have no @msg row:\n{}", missing.len(), missing.join("\n")); +} + +/// An SVG filter's refusal shows in the interface language whole, with the limits, element and +/// attribute names and the XML parser's position as given; the error the command returns stays +/// English. +#[test] +fn svg_filter_refusals_translate_with_their_values() { + let refuse = |xml: &str| { + let e = vectorcraft_effects::svg_filter::check(xml).expect_err("refused"); + vectorcraft_engine::EngineError::BadParams { cmd: "svgFilter.define".into(), msg: e }.to_string() + }; + let fe = |inner: &str| refuse(&format!("{inner}")); + let deep = format!("{}{}", "".repeat(20), "".repeat(20)); + let errors = [ + (refuse(""), "isn't valid XML", vec![]), + (refuse(""), "needs an id", vec!["", "id"]), + (refuse(&format!("", "f".repeat(256))), "characters", vec!["id", "255"]), + (fe("