diff --git a/ROADMAP.md b/ROADMAP.md index 879133f4c7..04eb95f38f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. @@ -142,6 +143,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 58b52dd651..4d578b8dcc 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -140,7 +140,7 @@ impl crate::Document { /// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the /// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para` /// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each -/// label's alignment. +/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct LabelStyles { @@ -180,6 +180,14 @@ pub struct LabelStyles { /// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`]. #[serde(skip_serializing_if = "Option::is_none")] pub legend_rows: Option, + /// The object rows the axis lines and tick marks keep once set with the paint, stroke or Appearance controls + /// ([`LabelRows`]). They replace the default 0.5 pt black stroke; kept rows without paint draw none. `None`: the + /// default stroke. + #[serde(skip_serializing_if = "Option::is_none")] + pub axis_rows: Option, + /// The object rows the rings of a radar graph keep, as [`Self::axis_rows`]. `None`: the default 0.25 pt gray stroke. + #[serde(skip_serializing_if = "Option::is_none")] + pub ring_rows: Option, } impl LabelStyles { diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 85182e9f36..ab571e50b2 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -239,6 +239,190 @@ thread_local! { static LIVE_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// The art an object draws in Preview with the geometry effects in it applied, at every depth, as +/// plain art whose objects keep the ids of the objects they are drawn from: `None` when no geometry +/// effect in it changes what it draws. Effects are evaluated above this crate, so the engine +/// registers one with [`set_drawn_art`]. +pub type DrawnArt = fn(&SymbolBoxes<'_>, &Node) -> Option; + +static DRAWN_ART: OnceLock = OnceLock::new(); + +/// Register how the art an object draws with its geometry effects is found, for clicks and +/// marquees (the first registration stays). +pub fn set_drawn_art(f: DrawnArt) { + // Already set: the same engine, registered by another session. + let _ = DRAWN_ART.set(f); +} + +/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and +/// the box round everything that art can paint. +struct EvaluatedDrawn { + of: EvaluatedLive, + reach: Option, +} + +/// How many objects' drawn art [`drawn`] keeps on each thread. Every pointer move measures every +/// object with effects that it passes, so the art of all of a document's objects with effects is +/// kept, within [`LIVE_KEPT_SIZE`], not only the latest few as with live objects. +const DRAWN_KEPT: usize = 4096; + +thread_local! { + /// The drawn art [`drawn`] keeps, by object, and the sum of their sizes. + static DRAWN: RefCell<(HashMap, usize)> = RefCell::new((HashMap::new(), 0)); + /// Whether [`drawn`] gives no art: set while art it gave is tested ([`DrawnOff`]). + static DRAWN_OFF: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +thread_local! { + /// How many objects' drawn art [`drawn`] evaluated on this thread. + static DRAWN_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect +/// in it applied, and is tested as it is. +struct DrawnOff { + was: bool, +} + +impl DrawnOff { + fn set() -> Self { + Self { was: DRAWN_OFF.replace(true) } + } +} + +impl Drop for DrawnOff { + fn drop(&mut self) { + DRAWN_OFF.set(self.was); + } +} + +/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a +/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to +/// the region it clips to. +fn plain(mask: bool, f: impl FnOnce() -> T) -> T { + let _off = mask.then(DrawnOff::set); + f() +} + +/// The art object `n` draws with the geometry effects in it applied ([`set_drawn_art`]), empty when +/// none changes what it draws, and the box round everything that art can paint. `None` while +/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated +/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a +/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the +/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new +/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is +/// kept alone. +fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option)> { + let f = DRAWN_ART.get()?; + if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) { + return None; + } + let doc = symbols.document(); + let inputs = live_inputs(); + let kept = DRAWN.with_borrow(|(kept, _)| kept.get(&n.id).filter(|e| e.of.is_of(doc, n, inputs)).map(|e| (e.of.art.clone(), e.reach))); + if kept.is_some() { + return kept; + } + #[cfg(test)] + DRAWN_EVALUATED.with(|c| c.set(c.get() + 1)); + let art = f(symbols, n); + let reach = art.as_ref().and_then(|a| a.reach_bounds_with(symbols)); + let art = Rc::new(art.into_iter().collect::>()); + let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); + if !holds_placed(doc, n) { + let of = EvaluatedLive { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + inputs, + art: art.clone(), + size, + }; + DRAWN.with_borrow_mut(|(kept, total)| { + if let Some(old) = kept.remove(&n.id) { + *total = total.saturating_sub(old.of.size); + } + while kept.len() >= DRAWN_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE { + let Some(other) = kept.keys().next().copied() else { break }; + if let Some(old) = kept.remove(&other) { + *total = total.saturating_sub(old.of.size); + } + } + kept.insert(n.id, EvaluatedDrawn { of, reach }); + *total = total.saturating_add(size); + }); + } + Some((art, reach)) +} + +/// Is `n` an object whose art [`drawn`] evaluates: a path or compound path, or a group or layer with +/// geometry effects or fills and strokes of its own, which paint its members as their effects draw +/// them? +fn evaluates(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { guide, .. } => !guide, + NodeKind::Compound { .. } => true, + NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(), + _ => false, + } +} + +/// The art path or compound path `n` draws with its geometry effects ([`drawn`]) in Preview, or +/// group or layer `n` with geometry effects or fills and strokes of its own: `None` in outline +/// (`outline`, where the canvas draws no effects), for other objects, and when no geometry effect +/// changes what it draws. Also `None` for a clip group or layer whose art holds only its clipping +/// path and that path's strokes, not the art it clips: its members are then tested one by one. +fn drawn_art(symbols: &SymbolBoxes, n: &Node, outline: bool) -> Option>> { + if outline { + return None; + } + drawn(symbols, n).map(|(art, _)| art).filter(|art| !art.is_empty() && (!n.clips() || holds_clipped_art(n, art))) +} + +/// Does `art`, the drawn art of clip group or layer `n`, hold any of the objects `n` clips (its +/// members after the clipping path), or does `n` clip none? +fn holds_clipped_art(n: &Node, art: &[Node]) -> bool { + let clipped: HashSet = n.children().into_iter().flatten().skip(1).map(|c| c.id).collect(); + if clipped.is_empty() { + return true; + } + let mut found = false; + for a in art { + a.walk(&mut |c| found |= clipped.contains(&c.id)); + } + found +} + +/// `base`, a box round what `n` paints without its geometry effects, grown to hold the art they +/// draw ([`effects_reach`]). `None` when `base` is. +fn drawn_reach(symbols: &SymbolBoxes, n: &Node, base: Option) -> Option { + let base = base?; + Some(effects_reach(symbols, n).map_or(base, |r| base.union(r))) +} + +/// The box round the art that the geometry effects in `n` draw: that of its own art ([`drawn`]) +/// when it is evaluated ([`evaluates`]), else the union of its members' in a group, layer or +/// Intertwine group. `None` when +/// no geometry effect changes what it draws, and while a [`DrawnOff`] guard lives. +fn effects_reach(symbols: &SymbolBoxes, n: &Node) -> Option { + if DRAWN_OFF.get() { + return None; + } + if evaluates(n) { + return drawn(symbols, n).filter(|(art, _)| !art.is_empty()).and_then(|(_, reach)| reach); + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => { + children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, effects_reach(symbols, c))) + } + _ => None, + } +} + /// Topmost editable object under `p`. pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option { hit_test_skipping(doc, p, opt, &|_| false, true) @@ -365,6 +549,11 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; + // A layer whose own geometry effects reshape its art is hit where that art is drawn, which the + // general traversal finds ([`hit_children`]). + if drawn_art(symbols, layer, opt.outline).is_some() { + return false; + } if layer.clips() && let Some(clip) = children.first() { @@ -397,11 +586,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox } let skip = |id| seen.contains(&id); let mut chain = Vec::new(); - let hit = match &c.kind { + let hit = plain(i == 0 && layer.clips(), || match &c.kind { NodeKind::Group { .. } | NodeKind::Intertwine { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some(), NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some() || hit_leaf(c, p, opt, symbols).is_some(), _ => hit_leaf(c, p, opt, symbols).is_some(), - }; + }); if hit && seen.insert(c.id) { tops.push(c.id); } @@ -462,6 +651,23 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec) { let Some(children) = parent.children() else { return }; + // A group or layer whose own geometry effects reshape what it holds: the locked objects drawn + // under `p` ([`drawn_hit`]). + if !(parent.clips() && edits_inside(parent, opt.scope)) + && let Some(art) = drawn_art(symbols, parent, opt.outline) + { + let _off = DrawnOff::set(); + let mut list = |id: NodeId, _: HitKind| { + if let Some(locked) = locked_member(parent, id, opt) + && !out.contains(&locked) + { + out.push(locked); + } + out.len() >= MAX_LOCKED_AT + }; + art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut list)); + return; + } if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) { return; } @@ -474,7 +680,7 @@ fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox continue; } if c.locked { - if locked_hit(c, p, opt, symbols) { + if plain(i == 0 && parent.clips(), || locked_hit(c, p, opt, symbols)) { out.push(c.id); } continue; @@ -599,13 +805,26 @@ pub fn set_clip_region(f: ClipRegion) { /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { let mut found = false; - clip.walk(&mut |n| { - let visible = |e: &crate::Effect| e.visible; - found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)); + clip.walk(&mut |n| found |= has_own_effects(n)); + found +} + +/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible +/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. +fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool { + let mut found = false; + n.walk(&mut |c| { + found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol)); }); found } +/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes? +fn has_own_effects(n: &Node) -> bool { + let visible = |e: &crate::Effect| e.visible; + n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)) +} + /// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the /// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its /// path elements. @@ -748,15 +967,7 @@ pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_ /// hidden, when it can't be edited (`editable_only`), when it is the part of a Shaper group that /// isn't shown, or when `p` is outside its reach. fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editable_only: bool) -> bool { - if shaper_hides(parent, i, opt.scope) { - return false; - } - // Read-only samples can read locked/template art; hidden art never participates. - if !c.visible || editable_only && (c.locked || c.is_template()) { - return false; - } - // A ruler guide is picked by the guide commands, never by an object hit test. - if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + if !may_reach(parent, i, c, opt, editable_only) { return false; } // (An envelope's content sits where it was, not where the envelope draws it.) @@ -765,11 +976,28 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols || cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p)) } +/// Can a click hit `c`, the child `i` of `parent`, or something inside it, wherever it is? Not +/// when it is hidden, when it can't be edited (`editable_only`), when it is a ruler guide or a +/// guide while guides are locked or hidden, or when it is the part of a Shaper group that isn't +/// shown. +fn may_reach(parent: &Node, i: usize, c: &Node, opt: HitOptions, editable_only: bool) -> bool { + if shaper_hides(parent, i, opt.scope) { + return false; + } + // Read-only samples can read locked/template art; hidden art never participates. + if !c.visible || editable_only && (c.locked || c.is_template()) { + return false; + } + // A ruler guide is picked by the guide commands, never by an object hit test. + !(c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. })) +} + /// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except /// that paths and compound paths are measured by their control points ([`PathData::control_bounds`], /// which hold the curves) instead of along their curves, which a compound path of thousands of /// members takes milliseconds to do on every click and hover. The box only rules points out, and it -/// is at least as large, so the same objects are hit. +/// is at least as large, so the same objects are hit. It also holds the art that the geometry +/// effects in `c` draw ([`drawn_reach`]), wherever they move it. /// /// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option { @@ -778,10 +1006,10 @@ fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option { NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => { children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b)) } - _ => return c.reach_bounds_with(symbols), + _ => return drawn_reach(symbols, c, c.reach_bounds_with(symbols)), }; let o = c.appearance.outset(); - control.map(|b| b.inflate(o, o)) + drawn_reach(symbols, c, control.map(|b| b.inflate(o, o))) } /// The members of compound path `children` that a click at `p` within `tol` can touch, as one @@ -855,19 +1083,36 @@ fn hit_children( editable_only: bool, ) -> Option { let children = parent.children()?; - if parent.clips() - && let Some(clip) = children.first() - { - if let Some(kind) = clip_outline_hit(parent, clip, p, opt, symbols, editable_only).filter(|_| !skip(clip.id)) { + let clip = children.first().filter(|_| parent.clips()); + // The selection tools in isolation mode within a clip group (or a layer with a clipping mask) + // hit what it holds outside its clipping mask too. + let edited = clip.is_some() && opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); + // A group or layer whose own geometry effects reshape what it holds hits where that art is drawn. + let art = if edited { None } else { drawn_art(symbols, parent, opt.outline) }; + if let Some(clip) = clip { + // The clipping mask's outline first, where it is drawn. + let drawn_clip = art.as_deref().and_then(|a| a.first()).filter(|a| a.clips()).and_then(|a| a.children()?.first()); + let kind = match drawn_clip { + Some(drawn) => { + let takes = opt.clip_outlines && editable_only && may_reach(parent, 0, clip, opt, editable_only); + takes.then(|| clip_outline(drawn, p, opt)).flatten() + } + None => clip_outline_hit(parent, clip, p, opt, symbols, editable_only), + }; + if let Some(kind) = kind.filter(|_| !skip(clip.id)) { chain.push(clip.id); return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }); } - // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for - // the selection tools in isolation mode within it. - let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); - if !edited && !clip_contains(clip, p, opt.outline) { - return None; - } + } + if let Some(art) = art { + return drawn_hit(parent, &art, p, opt, symbols, skip, chain, editable_only); + } + // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it. + if let Some(clip) = clip + && !edited + && !clip_contains(clip, p, opt.outline) + { + return None; } for i in hit_order(parent, children, p) { let Some(c) = children.get(i) else { continue }; @@ -875,7 +1120,7 @@ fn hit_children( continue; } chain.push(c.id); - let hit = match &c.kind { + let hit = plain(i == 0 && clip.is_some(), || match &c.kind { // A sublayer whose Preview is off is clicked in outline, like an outline view. NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only), NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => { @@ -888,7 +1133,7 @@ fn hit_children( NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, skip, chain, editable_only) .or_else(|| hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 })), _ => hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }), - }; + }); if hit.is_some() { return hit; } @@ -897,6 +1142,123 @@ fn hit_children( None } +/// What a click at `p` hits in `art`, the art that group or layer `parent` draws with its own +/// geometry effects ([`drawn_art`]): the member of `parent` that the topmost object of the art hit +/// there is drawn from, found by its id, at the depth [`hit_children`] gives it, or `parent` itself, +/// when it is not a layer, for art of its own (its own fills and strokes). Where that member can't be hit (hidden, locked, +/// skipped, a guide, a Shaper group's part that isn't shown), the click goes on to the art below. +#[allow(clippy::too_many_arguments)] +fn drawn_hit( + parent: &Node, + art: &[Node], + p: Point, + opt: HitOptions, + symbols: &SymbolBoxes, + skip: &dyn Fn(NodeId) -> bool, + chain: &mut Vec, + editable_only: bool, +) -> Option { + let _off = DrawnOff::set(); + let mut found = None; + let mut accept = |id: NodeId, kind: HitKind| { + found = member_chain(parent, id, opt, skip, editable_only).map(|path| (path, kind)); + found.is_some() + }; + if !art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut accept)) { + return None; + } + let (path, kind) = found?; + let leaf = path.last().copied().unwrap_or(parent.id); + chain.extend(path); + Some(Hit { leaf, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }) +} + +/// The ids from a child of `parent` down to its member `id`, when a click may hit each of them +/// ([`may_reach`], and not passed over by `skip`); empty when `id` is `parent` itself, `parent` is +/// not a layer and `skip` does not pass over it. `None` otherwise, and when `id` is not in `parent`. +fn member_chain(parent: &Node, id: NodeId, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option> { + // A layer's own fills and strokes are not an object to select. + if id == parent.id { + return (!skip(id) && !parent.is_layer()).then(Vec::new); + } + let mut steps = vec![]; + if !path_to(parent, id, &mut steps) { + return None; + } + let reachable = steps.iter().all(|(n, i, c)| may_reach(n, *i, c, opt, editable_only) && !skip(c.id)); + reachable.then(|| steps.iter().map(|(_, _, c)| c.id).collect()) +} + +/// Each container from `n` down to its member `id`, with the index and the child it holds on the +/// way, into `path`. `false` when `id` is not in `n`. +fn path_to<'a>(n: &'a Node, id: NodeId, path: &mut Vec<(&'a Node, usize, &'a Node)>) -> bool { + for (i, c) in n.children().into_iter().flatten().enumerate() { + path.push((n, i, c)); + if c.id == id || path_to(c, id, path) { + return true; + } + path.pop(); + } + false +} + +/// The locked object [`locked_objects_at`] lists for member `id` of `parent`: the outermost object +/// with its own lock on, from a child of `parent` down to `id`, when a click may reach each of them +/// ([`may_reach`] with locked objects counted) and none is a locked or template layer, as +/// [`locked_children`] goes down. `None` otherwise. +fn locked_member(parent: &Node, id: NodeId, opt: HitOptions) -> Option { + let mut steps = vec![]; + if !path_to(parent, id, &mut steps) { + return None; + } + for (n, i, c) in steps { + if !may_reach(n, i, c, opt, false) || c.is_layer() && (c.locked || c.is_template()) { + return None; + } + if c.locked { + return Some(c.id); + } + } + None +} + +/// Does a click at `p` hit an object of `art` (the art [`drawn_art`] gives) that `accept` takes? The +/// objects are tried front first, the members of an Intertwine group in the order they are drawn at +/// `p` ([`hit_order`]), and `accept` is given the id and the hit kind of each object hit until it +/// takes one. +fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &mut dyn FnMut(NodeId, HitKind) -> bool) -> bool { + if !n.visible { + return false; + } + if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) { + return false; + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => { + // A layer with Preview off is clicked in outline, as [`hit_children`] clicks it. + let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt }; + if n.clips() + && let Some(clip) = children.first() + { + // The selection tools take a clipping path on its outline before the art it clips, + // as [`hit_children`] does. + if opt.clip_outlines + && clip.visible + && let Some(kind) = clip_outline(clip, p, opt) + && accept(clip.id, kind) + { + return true; + } + if !clip_contains(clip, p, opt.outline) { + return false; + } + } + hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))) + } + _ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)), + } +} + /// The order a click at `p` tries the children of `parent` in, front first: their stacking order /// from the top, except that in an Intertwine group the members are tried in the order they are /// drawn at `p`, from the top ([`crate::intertwine::tier_at`]). @@ -965,10 +1327,17 @@ thread_local! { /// What a click at `p` hits on leaf object `n`: its outline, strokes and fills, its frame or its /// bounds, by kind. Raster effects (drop shadows, glows, blurs) do not take clicks: the area they /// paint beyond the object is left out here and in [`cull_reach`], so a click there reaches the -/// object under it. +/// object under it. Except in outline, a path or compound path with geometry effects is hit by the +/// art they draw ([`drawn_art`]), its own geometry only where that art lies. fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { #[cfg(test)] LEAVES_TESTED.with(|c| c.set(c.get() + 1)); + // A path or compound path whose geometry effects reshape it is hit where its art is drawn, and + // not where its own geometry no longer paints. + if let Some(art) = drawn_art(symbols, n, opt.outline) { + let _off = DrawnOff::set(); + return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols)); + } match &n.kind { NodeKind::Path { path, rule, .. } => { if opt.outline @@ -1132,16 +1501,26 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option } // Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are // passed by without being measured. - if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) { + if !edits_contents(n) + && n.extras().shaper.is_none() + && drawn_reach(symbols, n, n.reach_bounds_with(symbols)).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) + { return None; } + // A group whose own geometry effects reshape its members hits where that art is drawn. + if matches!(n.kind, NodeKind::Group { .. }) + && let Some(art) = drawn_art(symbols, n, opt.outline) + { + let _off = DrawnOff::set(); + return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols)); + } match &n.kind { // A clip group only hits inside its clipping path. NodeKind::Group { children, clip } => { if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) { return None; } - children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) + children.iter().enumerate().rev().find_map(|(i, c)| plain(i == 0 && *clip, || hit_any(c, p, opt, symbols))) } // An intertwine group hits by its members, as on the canvas. NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)), @@ -1313,7 +1692,7 @@ impl FindPart<'_> { } let Ok(i) = u32::try_from(i) else { continue }; path.push(i); - if let Some(kind) = self.find(c, path, whole, outline) { + if let Some(kind) = plain(i == 0 && n.clips(), || self.find(c, path, whole, outline)) { return Some(kind); } path.pop(); @@ -1635,7 +2014,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit -/// the selection tools' clicks. +/// the selection tools' clicks. Except in outline, a path or compound path with geometry effects, and +/// the members of a group or layer with geometry effects of its own, are touched where the art those +/// effects draw lies ([`set_drawn_art`]), as clicks hit them. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { marquee_with(doc, r, scope, leaves, false, false) } @@ -1661,25 +2042,30 @@ 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 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 // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c - .iter() - .enumerate() - .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) - .map(|(_, c)| (c, Some(r), outline, None)) - .collect(), + Some(c) => { + // In an isolated clip group, its members by their own geometry, as clicks take + // them ([`edits_inside`]). + let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) }; + c.iter() + .enumerate() + .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) + .map(|(_, c)| (c, Some(r), outline, None, drawn.clone())) + .collect() + } // A single object isolated: only it. None => doc .parent_of(s.id) .and_then(|p| doc.node(p)) .and_then(|p| p.children()) .into_iter() - .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None))) + .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None, None))) .collect(), }, // The objects of the layers, looking through sublayers (hidden, locked and template ones @@ -1688,36 +2074,80 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, r, outline)) + .flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of /// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`, /// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain - /// shapes ([`mask_marquee`]). - fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec> { + /// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object + /// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around + /// `l` has such effects. + fn layer_objects<'a>( + l: &'a Node, + s: &SymbolBoxes, + r: Rect, + outline: bool, + whole_compounds: bool, + drawn: Option>>, + ) -> Vec> { let mut out = vec![]; let outline = outline || previews_off(l); + let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline)); let inner = marquee_in_parent(l, r, outline); for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { - if let Some(inner) = inner + if let Some(inner) = if drawn.is_some() { Some(r) } else { inner } && c.visible && !c.locked && !c.is_template() { - out.extend(layer_objects(c, inner, outline)); + out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone())); } } else if !c.is_ruler_guide() { - if i == 0 && l.clips() { - out.push((c, mask_marquee(l, r), outline, Some(r))); + if drawn.is_some() { + out.push((c, Some(r), outline, None, drawn.clone())); + } else if i == 0 && l.clips() { + out.push((c, mask_marquee(l, r), outline, Some(r), None)); } else if inner.is_some() { - out.push((c, inner, outline, None)); + out.push((c, inner, outline, None, None)); } } } out } + /// The ids of the objects of the art that group or layer `n` draws with its own geometry + /// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them. + /// `None` in outline and when it has no such effects. + fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option>> { + let art = drawn_art(s, n, outline)?; + let _off = DrawnOff::set(); + let mut ids = vec![]; + for a in art.iter().filter(|a| a.visible) { + collect_leaves(a, s, r, None, whole_compounds, false, &mut ids); + } + Some(Rc::new(ids.into_iter().collect())) + } + /// The objects inside `n` that a marquee collects ([`collect_leaves`]) whose ids are in + /// `drawn` ([`touched_in_art`]), into `out`: leaves, and groups whose own fills and strokes + /// the art paints there. + fn collect_drawn(n: &Node, drawn: &HashSet, scope: Option, out: &mut Vec) { + for (i, c) in n.children().into_iter().flatten().enumerate() { + if !c.visible || c.locked || shaper_hides(n, i, scope) { + continue; + } + if is_leaf(c) { + if drawn.contains(&c.id) { + out.push(c.id); + } + } else { + if drawn.contains(&c.id) && !c.is_layer() { + out.push(c.id); + } + collect_drawn(c, drawn, scope, out); + } + } + } /// The part of `r` in which the marquee can touch the clipping path of `parent` by its own /// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its /// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to. @@ -1750,6 +2180,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// compound paths, layers and groups are touched by their box. A clipping path is touched by /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { + // A path or compound path whose geometry effects reshape it, or a group or layer whose own + // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). + if let Some(art) = drawn_art(s, n, outline || previews_off(n)) { + let _off = DrawnOff::set(); + return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false)); + } match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { @@ -1759,7 +2195,8 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh c.visible && !shaper_hides(n, i, scope) && if i == 0 && n.clips() { - mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline) + plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))) + || clip_edge_touches(c, r, outline) } else { inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) } @@ -1813,6 +2250,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { let outline = outline || previews_off(n); + // The members that the art its own geometry effects draw touches, and a group whose + // own fills and strokes that art paints, as clicks hit it ([`member_chain`]). + if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) { + if drawn.contains(&n.id) && !n.is_layer() { + out.push(n.id); + } + collect_drawn(n, &drawn, scope, out); + return; + } let inner = marquee_in_parent(n, r, outline); for (i, c) in children.iter().enumerate() { if !c.visible || c.locked || shaper_hides(n, i, scope) { @@ -1821,7 +2267,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if i == 0 && n.clips() { let before = out.len(); if let Some(r) = mask_marquee(n, r) { - collect_leaves(c, s, r, scope, whole_compounds, outline, out); + plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out)); } if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { out.push(c.id); @@ -1838,12 +2284,33 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } } } - let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); - for (t, r, outline, edge) in tops { + for (t, r, outline, edge, drawn) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; } + // In a layer or isolated container whose own geometry effects reshape its art: by what + // that art touches. + if let Some(drawn) = drawn { + if !leaves { + let mut touched = false; + t.walk(&mut |n| touched |= drawn.contains(&n.id)); + if touched { + out.push(t.id); + } + } else { + // A leaf, or a group whose own fills and strokes the art paints, and its members. + if drawn.contains(&t.id) && !t.is_layer() { + out.push(t.id); + } + if !is_leaf(t) { + collect_drawn(t, &drawn, scope, &mut out); + } + } + continue; + } + // A layer's clipping mask counts by its own geometry ([`plain`]). + let _mask = edge.is_some().then(DrawnOff::set); if leaves { let before = out.len(); if let Some(r) = r { @@ -1863,8 +2330,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which /// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a -/// layer, the marquee whose edge test it also takes (`clip_edge_touches`). -type Top<'a> = (&'a std::sync::Arc, Option, bool, Option); +/// layer, the marquee whose edge test it also takes (`clip_edge_touches`), and in a layer or an +/// isolated container whose own geometry effects reshape its art, the ids of the objects of that art +/// the marquee touches (`touched_in_art`). +type Top<'a> = (&'a std::sync::Arc, Option, bool, Option, Option>>); /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a /// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 9ca784c1f4..39efd78795 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -307,6 +307,423 @@ fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() { assert!(again < groups / 8, "{again} of {groups} regions evaluated again"); } +/// A stand-in for the engine's [`DrawnArt`]: an object with a visible effect named `test.shift` +/// draws 100 pt to the right of its own place, and one with a visible effect named `test.copy` +/// draws at its own place and 100 pt to the right. The effects are applied innermost first, and +/// the art keeps the ids of the objects it is drawn from. An instance of a symbol whose art has a +/// visible effect draws as a 50 pt square from (100, 0), white with a black 1 pt stroke. A clip +/// group with a visible effect named `test.mask_only` draws as a group of its clipping path alone, +/// as the engine's art for a clip group whose clipping path's strokes have geometry effects is. +/// Without any of these, no geometry effect changes what an object draws. +fn shifted_art(s: &SymbolBoxes<'_>, n: &Node) -> Option { + if n.clips() + && n.appearance.effects.iter().any(|e| e.visible && e.id == "test.mask_only") + && let Some(mask) = n.children().and_then(|c| c.first()) + { + return Some(Node::group(n.id, vec![mask.clone()])); + } + fn draw(s: &SymbolBoxes<'_>, n: &Node, found: &mut bool) -> Node { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && s.has_effects(symbol) + { + *found = true; + return Node::path(n.id, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art()); + } + let mut m = n.clone(); + if let Some(children) = m.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(draw(s, c, found)); + } + } + let has = |id: &str| n.appearance.effects.iter().any(|e| e.visible && e.id == id); + let (shift, copy) = (has("test.shift"), has("test.copy")); + m.appearance.effects.retain(|e| e.id != "test.shift" && e.id != "test.copy"); + *found |= shift || copy; + let shifted = |m: &Node| moved(m, vectorcraft_geom::Affine::translate((100.0, 0.0))); + if shift { + shifted(&m) + } else if copy { + Node::group(n.id, vec![Arc::new(shifted(&m)), Arc::new(m)]) + } else { + m + } + } + let mut found = false; + let art = draw(s, n, &mut found); + found.then_some(art) +} + +/// A visible effect named `id`. +fn effect(id: &str) -> crate::Effect { + crate::Effect { id: id.into(), params: serde_json::json!({}), visible: true } +} + +/// A 50 pt square at `x`, `y`, white with a black 1 pt stroke. +fn square(d: &mut Document, x: f64, y: f64) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 50.0, y + 50.0)), Appearance::default_art()) +} + +/// The leaf and the kind a click at (`x`, `y`) hits. +fn hit_at(d: &Document, x: f64, y: f64, opt: HitOptions) -> Option<(NodeId, HitKind)> { + hit_test(d, Point::new(x, y), opt).map(|h| (h.leaf, h.kind)) +} + +/// A path that a geometry effect moves is clicked where it is drawn, and not at its own place, +/// which it no longer paints; with Object Selection by Path Only on its drawn outline, not its +/// fill. Outline view draws no effects: there its own outline is clicked. Hidden, the effect no +/// longer moves what clicks hit. +#[test] +fn a_click_hits_a_paths_shifted_art_not_its_source() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut p = square(&mut d, 0.0, 0.0); + p.appearance.effects.push(effect("test.shift")); + let a = p.id; + d.insert(Some(l), 0, p).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)), "where it is drawn"); + assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place"); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a]); + assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty()); + let path_only = HitOptions { path_only: true, ..opt }; + assert_eq!(hit_at(&d, 125.0, 25.0, path_only), None, "path only: the drawn fill"); + assert_eq!(hit_at(&d, 100.0, 25.0, path_only), Some((a, HitKind::Stroke)), "path only: the drawn outline"); + let outline = HitOptions { outline: true, ..opt }; + assert_eq!(hit_at(&d, 0.5, 25.0, outline), Some((a, HitKind::Outline)), "outline: its own outline"); + assert_eq!(hit_at(&d, 100.5, 25.0, outline), None, "outline: no drawn art"); + d.node_mut(a).unwrap().appearance.effects[0].visible = false; + assert_eq!(hit_at(&d, 25.0, 25.0, opt), Some((a, HitKind::Fill)), "hidden effect: its own place"); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "hidden effect: nothing drawn there"); +} + +/// A geometry effect that copies a path is clicked on the copy and on the path, the topmost of the +/// stack first. The pointer moving over it evaluates its art once until it changes, and a path +/// without effects is not evaluated. +#[test] +fn a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let below = square(&mut d, 100.0, 0.0); + let mut p = square(&mut d, 0.0, 0.0); + p.appearance.effects.push(effect("test.copy")); + let (a, b) = (p.id, below.id); + d.insert(Some(l), 0, below).unwrap(); + d.insert(Some(l), 1, p).unwrap(); + let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let opt = HitOptions::default(); + for _ in 0..3 { + assert_eq!(hit_at(&d, 25.0, 25.0, opt).map(|h| h.0), Some(a), "the path"); + assert_eq!(hit_at(&d, 125.0, 25.0, opt).map(|h| h.0), Some(a), "its copy, over the square below"); + } + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a, b]); + assert_eq!(evaluated(), before + 1, "evaluated once"); + if let Some(NodeKind::Path { path, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *path = shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 50.0)); + } + assert_eq!(hit_at(&d, 140.0, 25.0, opt).map(|h| h.0), Some(b), "narrowed, the copy leaves the square below"); + assert_eq!(evaluated(), before + 2, "evaluated again after it changed"); + // The square below has no effects: it is never evaluated. + assert_eq!(hit_at(&d, 145.0, 45.0, opt).map(|h| h.0), Some(b)); + assert_eq!(evaluated(), before + 2); +} + +/// A group without effects or fills and strokes of its own is not evaluated as a whole: a click +/// on the art of a moved member in it evaluates that member only, and finds the group by it. +#[test] +fn a_click_in_a_plain_group_evaluates_only_its_member_with_effects() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut moved = square(&mut d, 0.0, 0.0); + moved.appearance.effects.push(effect("test.shift")); + let still = square(&mut d, 0.0, 100.0); + let (a, g) = (moved.id, d.alloc_id()); + d.insert(Some(l), 0, Node::group(g, vec![Arc::new(moved), Arc::new(still)])).unwrap(); + let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let opt = HitOptions::default(); + for _ in 0..3 { + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill))); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]); + } + assert_eq!(evaluated(), before + 1, "only the member with effects, once"); +} + +/// A compound path that a geometry effect moves keeps its hole where it is drawn, for clicks and +/// marquees. +#[test] +fn a_compound_paths_shifted_art_keeps_its_hole() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let outer = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 60.0)), Appearance::default()); + let hole = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default()); + let c = d.alloc_id(); + let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd }); + compound.appearance = Appearance::default_art().into(); + compound.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, compound).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 105.0, 5.0, opt), Some((c, HitKind::Fill)), "its drawn fill"); + assert_eq!(hit_at(&d, 130.0, 30.0, opt), None, "its drawn hole"); + assert_eq!(hit_at(&d, 5.0, 5.0, opt), None, "its own place"); + assert_eq!(marquee(&d, Rect::new(155.0, 25.0, 165.0, 35.0), None, false), [c], "a marquee across the drawn edge"); + assert!(marquee(&d, Rect::new(-5.0, 25.0, 5.0, 35.0), None, false).is_empty(), "a marquee across its own edge"); +} + +/// A marquee touches a path that a geometry effect moves where it is drawn, and not at its own +/// place; in Outline view, at its own place. +#[test] +fn a_marquee_touches_a_paths_shifted_art_not_its_source() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut p = square(&mut d, 0.0, 0.0); + p.appearance.effects.push(effect("test.shift")); + let a = p.id; + d.insert(Some(l), 0, p).unwrap(); + let (drawn, own) = (Rect::new(140.0, 40.0, 160.0, 60.0), Rect::new(40.0, 40.0, 60.0, 60.0)); + for leaves in [false, true] { + assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn"); + assert!(marquee(&d, own, None, leaves).is_empty(), "its own place"); + assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art"); + assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place"); + } +} + +/// A group whose own geometry effect moves its members is clicked where each member is drawn: the +/// member, inside the group, is hit, and a locked member lets the click through to what is below +/// and is listed for unlocking there. A marquee there touches the group, or the member for Direct +/// Selection. +#[test] +fn a_groups_own_effect_moves_where_its_members_are_hit() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let below = square(&mut d, 150.0, 0.0); + let (a, b) = (square(&mut d, 0.0, 0.0), square(&mut d, 50.0, 0.0)); + let (below_id, a_id, b_id, g) = (below.id, a.id, b.id, d.alloc_id()); + let mut group = Node::group(g, vec![Arc::new(a), Arc::new(b)]); + group.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, below).unwrap(); + d.insert(Some(l), 1, group).unwrap(); + let opt = HitOptions::default(); + let h = hit_test(&d, Point::new(125.0, 25.0), opt).unwrap(); + assert_eq!((h.leaf, h.top_object(None)), (a_id, g), "the first member, drawn there"); + assert_eq!(h.ancestry, [l, g, a_id]); + assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(b_id), "the second member, over the square below"); + assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "the first member's own place"); + assert_eq!(objects_at(&d, Point::new(175.0, 25.0), opt, None), [g, below_id]); + let drawn = Rect::new(195.0, 20.0, 205.0, 30.0); + assert_eq!(marquee(&d, drawn, None, false), [below_id, g]); + assert_eq!(marquee(&d, drawn, None, true), [below_id, b_id]); + assert!(marquee(&d, Rect::new(-5.0, 20.0, 5.0, 30.0), None, true).is_empty(), "the members' own place"); + d.node_mut(b_id).unwrap().locked = true; + assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(below_id), "a locked member lets the click through"); + assert_eq!(marquee(&d, drawn, None, true), [below_id], "nor does a marquee collect it"); + assert_eq!(locked_objects_at(&d, Point::new(175.0, 25.0), opt), [b_id], "the Unlock submenu lists it where it is drawn"); + assert!(locked_objects_at(&d, Point::new(75.0, 25.0), opt).is_empty(), "and not at its own place"); + // Outline view draws no effects: the members are clicked at their own places. + let outline = HitOptions { outline: true, ..opt }; + assert_eq!(hit_at(&d, 0.5, 25.0, outline).map(|h| h.0), Some(a_id)); +} + +/// A layer whose own geometry effect moves its art is clicked and marqueed where the art is +/// drawn. With the layer's Preview off, its art is clicked at its own place, in outline. +#[test] +fn a_layers_own_effect_moves_where_its_art_is_hit() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let a = square(&mut d, 0.0, 0.0); + let a_id = a.id; + d.insert(Some(l), 0, a).unwrap(); + d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift")); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "where it is drawn"); + assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place"); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a_id]); + assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty()); + let (drawn, own) = (Rect::new(145.0, 20.0, 155.0, 30.0), Rect::new(-5.0, 20.0, 5.0, 30.0)); + for leaves in [false, true] { + assert_eq!(marquee(&d, drawn, None, leaves), [a_id], "a marquee where it is drawn"); + assert!(marquee(&d, own, None, leaves).is_empty(), "a marquee at its own place"); + } + if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(l).map(|n| &mut n.kind) { + *preview = false; + } + assert_eq!(hit_at(&d, 0.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: its own outline"); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: no drawn art"); + assert_eq!(marquee(&d, own, None, false), [a_id], "preview off: a marquee at its own place"); +} + +/// In a layer whose own geometry effect moves its art, a sublayer with Preview off is clicked in +/// outline: on the outline of its art where the art is drawn, not inside its fill. +#[test] +fn a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let sub = d.alloc_id(); + d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap(); + let a = square(&mut d, 0.0, 0.0); + let a_id = a.id; + d.insert(Some(sub), 0, a).unwrap(); + d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift")); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "preview on: inside its fill"); + if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(sub).map(|n| &mut n.kind) { + *preview = false; + } + assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: inside its fill"); + assert_eq!(hit_at(&d, 100.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: on its outline"); +} + +/// A group with fills and strokes of its own around an instance of a symbol whose art has an +/// effect is clicked where its art is drawn, though no object in the group has an effect. +#[test] +fn a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let mut art = square(&mut d, 0.0, 0.0); + art.appearance.effects.push(effect("test.raster")); + d.symbols.push(crate::Symbol { dynamic: false, name: "Effected".into(), art: Arc::new(art) }); + let (g, inst) = (d.alloc_id(), d.alloc_id()); + let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: "Effected".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + let mut group = Node::group(g, vec![Arc::new(instance)]); + group.appearance = Appearance::default_art().into(); + d.insert(Some(l), 0, group).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((inst, HitKind::Fill)), "where its art is drawn"); + assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]); +} + +/// In a layer with fills and strokes of its own whose art is evaluated for a member's geometry +/// effect, an Intertwine group's members are still clicked in the order they are drawn at the +/// click: where the lower member is woven over the upper one, the click takes the lower member. +#[test] +fn an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order() { + set_drawn_art(shifted_art); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + d.node_mut(l).unwrap().appearance = Appearance::default_art().into(); + let mut a = square(&mut d, 0.0, 100.0); + a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(25.0, 100.0, 50.0, 150.0)))); + let b = square(&mut d, 25.0, 100.0); + let (a_id, b_id, g) = (a.id, b.id, d.alloc_id()); + d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap(); + let mut moved = square(&mut d, 200.0, 0.0); + moved.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 1, moved).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 40.0, 125.0, opt), Some((a_id, HitKind::Fill)), "where the lower member is woven over"); + assert_eq!(hit_at(&d, 60.0, 125.0, opt), Some((b_id, HitKind::Fill)), "where the upper member is drawn over"); +} + +/// The clipping path of a clip group and of a clipping layer is still marqueed by its own geometry +/// when a geometry effect moves what it draws. +#[test] +fn a_clipping_path_keeps_its_own_geometry_under_a_geometry_effect() { + set_drawn_art(shifted_art); + let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); + // A clip group. + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(effect("test.shift")); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clip group"); + // A clipping layer. + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(effect("test.shift")); + let (mask_id, art_id) = (mask.id, art.id); + let layer = d.node_mut(l).unwrap(); + if let NodeKind::Layer { children, clip, .. } = &mut layer.kind { + (*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true); + } + assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clipping layer"); +} + +/// The selection tools take the clipping path of a clip group whose own geometry effect moves it +/// on its outline where it is drawn, before the art it clips, and not at its own place. +#[test] +fn a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit() { + set_drawn_art(shifted_art); + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + clip.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, clip).unwrap(); + let tools = HitOptions { clip_outlines: true, ..HitOptions::default() }; + assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "the drawn edge, over the art"); + assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "the drawn art inside the mask"); + assert_eq!(hit_at(&d, 0.5, 50.0, tools), None, "the mask's own edge"); + // The same clip group in a group whose own effect moves it. + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + outer.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, outer).unwrap(); + assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "in a moved group: the drawn edge, over the art"); + assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "in a moved group: the drawn art"); +} + +/// In isolation mode in a clip group whose own geometry effect moves it, the selection tools take +/// the art outside the clipping mask by its own geometry, for a marquee as for a click. +#[test] +fn an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry() { + set_drawn_art(shifted_art); + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + clip.appearance.effects.push(effect("test.shift")); + d.insert(Some(l), 0, clip).unwrap(); + let tools = HitOptions { clip_outlines: true, scope: Some(g), ..HitOptions::default() }; + assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "a click outside the mask"); + let edge = Rect::new(190.0, 40.0, 210.0, 60.0); + for leaves in [false, true] { + assert_eq!(marquee(&d, edge, Some(g), leaves), [art_id], "a marquee across its own edge outside the mask"); + } +} + +/// A clip group whose drawn art holds only its clipping path still has the art it clips clicked +/// inside the mask. +#[test] +fn a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path() { + set_drawn_art(shifted_art); + let mut d = Document::new(400.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + clip.appearance.effects.push(effect("test.mask_only")); + d.insert(Some(l), 0, clip).unwrap(); + let opt = HitOptions::default(); + assert_eq!(hit_at(&d, 50.0, 50.0, opt), Some((art_id, HitKind::Fill)), "inside the mask"); + assert_eq!(objects_at(&d, Point::new(50.0, 50.0), opt, None), [g]); + assert!(hit_at(&d, 150.0, 50.0, opt).is_none(), "outside the mask"); +} + /// Every test of a clip group by its clipping path follows the region a live effect moved it to: /// the selected art hidden by the mask, a click into a group holding the clip group, the locked /// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 63951d8104..6d2c14a102 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -384,14 +384,14 @@ pub fn override_paints(n: &Node) -> impl Iterator { n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten() } -/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its -/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out. +/// The paints a graph keeps for its series, its labels and its lines ([`crate::graph::GraphSpec`]), which +/// its marks, labels and lines take each time it is drawn again and which [`node_paints`] leaves out. pub fn graph_paints(n: &Node) -> impl Iterator { let g = n.extras().graph.as_deref(); let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten(); let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten(); let l = g.map(|g| &g.label_styles); - let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten(); + let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows, &l.axis_rows, &l.ring_rows]).flatten(); series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten()) } @@ -400,7 +400,7 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue; - assert_eq!(d.map_solid_paints(&mut to_blue), 5); + assert_eq!(d.map_solid_paints(&mut to_blue), 7); let g = d.node(a).unwrap().extras().graph.clone().unwrap(); assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand"))); assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand"))); let legend = g.label_styles.legend.unwrap(); assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None)); assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand"))); + assert_eq!(g.label_styles.axis_rows.unwrap().paint.stroke, Some(linked(blue, "Brand"))); + assert_eq!(g.label_styles.ring_rows.unwrap().paint.stroke, Some(linked(blue, "Brand"))); let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None); - assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four"); + assert_eq!(d.map_paints(&mut cleared), 7, "the fill and the graph's six"); assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none)); } diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 9de39458b0..6863960230 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -35,7 +35,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 29313ccb22..15a0fbbd40 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -32,6 +32,16 @@ fn outline(n: &Node, out: &mut PathData) { } } +/// The outline area type wraps around for wrap object `n`, in document coordinates, as +/// [`resolve_wrap`] makes it: a path's subpaths that are closed or have more than two anchors, those +/// of the shown members of a group or compound path, a clip group's clipping object's, and the +/// bounds of other art. Empty when `n` has none. +pub fn wrap_outline(n: &Node) -> PathData { + let mut pd = PathData::default(); + outline(n, &mut pd); + pd +} + enum Item<'a> { Wrap(&'a Node), Text(&'a Node), diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index f9e2669bff..5e95244e26 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -683,9 +683,11 @@ fn apart(offsets: &[Vec2], b: Rect) -> bool { /// Type `n` whose own geometry effects only move it ([`transform_moves`]) as a group of the moved /// type ([`moved_type`]). The group keeps `n`'s id, name, visibility, transparency, opacity mask and -/// remaining (raster) effects, and the type in it has none of them. `None` otherwise. +/// remaining (raster) effects, and the type in it has none of them. `None` otherwise, and for type +/// whose copies each carry the raster effects listed before their Transform effect +/// ([`crate::outer_effects`]), which is baked through its outlines as the canvas draws it. fn moved_type_group(n: &Node) -> Option { - if !matches!(n.kind, NodeKind::Text(_)) { + if !matches!(n.kind, NodeKind::Text(_)) || crate::reshape::copied_raster_at(n).is_some() { return None; } let moves = transform_moves(&geometry_effects(n))?; diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index cac3711593..d38440af75 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -182,7 +182,7 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}), ), g( @@ -217,7 +217,7 @@ pub fn effect_catalog() -> Vec { CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aa95c8cfdd..6c6bec1387 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -87,8 +87,8 @@ pub use raster::{ }; pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry, - has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art, - outline_text, paint_type_piece, reshape, + has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, + outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 7f7f1099e3..697a217da9 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -168,6 +168,62 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr if sign < 0.0 { footprint.reverse_subpaths() } else { footprint } } +/// The most edges a facet may have for [`seamed_fill`] to test it for crossing edges. +const SEAMED_FILL_EDGES: usize = 256; + +/// Facet `path` and its round seam `seam` wide as one path to fill ([`footprint`]), so that at an +/// edge pixel the facet and its seam cover it once between them, not a fill's coverage and then a +/// stroke's over it. `None` unless `path` is one closed polygon of up to [`SEAMED_FILL_EDGES`] +/// finite edges, with an area, and with no two edges that are not neighbors touching: only there +/// does the footprint's nonzero fill cover the facet and its seam and nothing more. `None` too for +/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area +/// than the facet. +pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option { + use kurbo::{PathEl, Point, Shape}; + if !(seam.is_finite() && seam > 0.0) { + return None; + } + let bez = path.to_bezpath(); + let mut elements = bez.elements().iter(); + let Some(PathEl::MoveTo(first)) = elements.next() else { return None }; + let mut points = vec![*first]; + let mut closed = false; + for el in elements { + match el { + PathEl::LineTo(p) if !closed => points.push(*p), + PathEl::ClosePath if !closed => closed = true, + _ => return None, + } + } + if points.len() > 1 && points.first() == points.last() { + points.pop(); + } + let area = bez.area().abs(); + if !closed || !(3..=SEAMED_FILL_EDGES).contains(&points.len()) || points.iter().any(|p| !p.is_finite()) || !area.is_finite() || area <= 1e-9 { + return None; + } + let side = |a: Point, b: Point, c: Point| (b - a).cross(c - a); + let touch = |a: Point, b: Point, c: Point, d: Point| { + let boxes = a.x.min(b.x) <= c.x.max(d.x) && c.x.min(d.x) <= a.x.max(b.x) && a.y.min(b.y) <= c.y.max(d.y) && c.y.min(d.y) <= a.y.max(b.y); + boxes && side(a, b, c) * side(a, b, d) <= 0.0 && side(c, d, a) * side(c, d, b) <= 0.0 + }; + let n = points.len(); + let edge = |i: usize| (points[i], points[(i + 1) % n]); + for i in 0..n { + for j in i + 2..n { + if i == 0 && j == n - 1 { + continue; + } + let ((a, b), (c, d)) = (edge(i), edge(j)); + if touch(a, b, c, d) { + return None; + } + } + } + let fill = footprint(&bez, seam); + (fill.bounding_box().is_finite() && fill.area().abs() >= area).then(|| vectorcraft_geom::PathData::from_bezpath(&fill)) +} + /// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same /// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets' /// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave @@ -236,7 +292,9 @@ pub(crate) fn underlay( /// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each /// channel, an underlay of the facets with wide seams lies under the facets themselves, so a /// shared edge is opaque in that channel's own light before the channels are screened together; -/// the black backdrop shows only outside the surface, which the clip removes. +/// the black backdrop shows only outside the surface, which the clip removes. Each facet over the +/// underlay is one fill of the facet and its seam together ([`seamed_fill`]), or a fill and a seam +/// stroke where that is `None`. pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node { use kurbo::Shape; use std::sync::Arc; @@ -260,6 +318,8 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t let clip = Node::path(id, PathData::from_bezpath(&boundary), Appearance::default()); let bounds = bounds.unwrap_or(Rect::ZERO).inflate(1.0, 1.0); let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0)); + let seam = |face: &vectorcraft_three_d::Facet| (face.thickness() / 2.0).clamp(0.05, 0.75); + let exact: Vec> = facets.iter().map(|face| seamed_fill(&face.path(), seam(face))).collect(); let channels = (0..3) .map(|channel| { let mut color = [0.0; 3]; @@ -295,7 +355,17 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t }; let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))]; children.extend(draw(|_| UNDERLAY_SEAM)); - children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75))); + children.extend(facets.iter().zip(&exact).zip(&paints).map(|((face, fill), paint)| { + let mut items = vec![AppearanceItem::Fill(FillLayer::new(paint.clone()))]; + let path = match fill { + Some(fill) => fill.clone(), + None => { + items.push(AppearanceItem::Stroke(seam_stroke(paint.clone(), seam(face)))); + face.path() + } + }; + Arc::new(Node::path(id, path, Appearance { items, ..Default::default() })) + })); let mut group = Node::group(id, children); group.isolate = true; group.blend = BlendMode::Screen; @@ -538,4 +608,65 @@ mod tests { } } } + + /// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the + /// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound + /// either way and in a concave notch. A facet whose footprint would gain or lose area under a + /// nonzero fill (no area, crossing edges, a hole, curves) or a seam with no width has none. + #[test] + fn seamed_fill_covers_a_polygon_and_its_seam_once() { + use kurbo::Shape; + use vectorcraft_geom::BezPath; + let polygon = |points: &[(f64, f64)]| { + let mut bp = BezPath::new(); + bp.move_to(points[0]); + for p in &points[1..] { + bp.line_to(*p); + } + bp.close_path(); + bp + }; + let covers = |fill: &vectorcraft_geom::PathData, x: f64, y: f64| fill.to_bezpath().winding(Point::new(x, y)) != 0; + let notched = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (6.0, 10.0), (6.0, 4.0), (4.0, 4.0), (4.0, 10.0), (0.0, 10.0)]; + let mut reversed = notched; + reversed.reverse(); + for points in [¬ched[..], &reversed[..], &[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)][..]] { + let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(points)), 0.75).expect("a simple polygon"); + let contours = fill.to_bezpath().elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count(); + assert!(contours >= 2, "{points:?}: the seam's outline and the facet, {contours} contours"); + for (x, y) in [(1.0, 1.0), (2.0, 0.5), (5.0, -0.3), (-0.3, 5.0), (-0.2, -0.2)] { + assert!(covers(&fill, x, y), "{points:?} covers ({x},{y})"); + } + for (x, y) in [(5.0, -0.5), (-0.5, 5.0), (-0.3, -0.3), (12.0, 12.0)] { + assert!(!covers(&fill, x, y), "{points:?} leaves ({x},{y})"); + } + } + let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(¬ched)), 0.75).unwrap(); + assert!(covers(&fill, 4.3, 8.0) && covers(&fill, 5.0, 4.3), "the notch's edges carry the seam"); + assert!(!covers(&fill, 5.0, 8.0), "the notch stays open"); + let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let mut holed = square.clone(); + holed.extend(polygon(&[(3.0, 3.0), (3.0, 7.0), (7.0, 7.0), (7.0, 3.0)]).iter()); + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.quad_to((5.0, -5.0), (10.0, 0.0)); + curved.line_to((5.0, 10.0)); + curved.close_path(); + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((10.0, 0.0)); + open.line_to((10.0, 10.0)); + for (name, path, seam) in [ + ("sliver", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)]), 0.75), + ("bow tie", polygon(&[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)]), 0.75), + ("a vertex visited twice", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 5.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0)]), 0.75), + ("hole", holed, 0.75), + ("curve", curved, 0.75), + ("open", open, 0.75), + ("no seam", square.clone(), 0.0), + ("endless seam", square, f64::INFINITY), + ] { + assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&path), seam).is_none(), "{name}"); + } + } } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c3238199a2..172eab2348 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -111,20 +111,29 @@ fn reaches_appearance(e: &Effect) -> bool { /// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, /// baked and expanded through that art ([`reshape`]). pub fn has_transform_art(n: &Node) -> bool { - has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some() + has_gradient_copies(n) + || has_layered_copies(n) + || has_transform_options(n) + || has_painted_effects(n) + || (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some()) } -/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform -/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index -/// of the last visible Transform effect that makes copies, when a visible raster effect that -/// follows a Transform effect ([`crate::raster::follows`]) 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 path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect -/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of -/// its own. +/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so +/// that each copy of a Transform effect carries the raster effects listed before that effect +/// ([`copied_raster_art`]): the index of the last visible Transform effect that makes copies, when +/// a visible raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed +/// before it and every other visible effect before it is a geometry effect or such a raster effect. +/// `None` otherwise, and for an object with a linked opacity mask, a 3D effect, Crop Marks, Vector +/// Halftone, a live-effect plug-in that paints what it returns, a fill or stroke that paints with +/// geometry effects of its own, or (type, images and symbol instances) a perspective. pub(crate) fn copied_raster_at(n: &Node) -> Option { - if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) { - return None; + match n.kind { + NodeKind::Path { guide: false, clipping: false, .. } + | NodeKind::Compound { .. } + | NodeKind::Text(_) + | NodeKind::Image(_) + | NodeKind::SymbolInstance { .. } => {} + _ => return None, } let effects = &n.appearance.effects; // Checked first: this runs for every object drawn. @@ -143,7 +152,8 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option { || crate::has_crop_marks(n) || crate::addons::halftone::has_halftone(n) || has_painted_effects(n) - || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())); + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); (carried && !excluded).then_some(t) } @@ -890,6 +900,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod as_art(doc, n, symbol_art) } +/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the +/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`] +/// gives. `None` for other kinds of objects and for an instance without `symbol_art`. +pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { + if !matches!(n.kind, NodeKind::SymbolInstance { .. }) { + return None; + } + as_art(doc, n, symbol_art) +} + /// [`reshape`] without its checks (no geometry effects: just the art). pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default()) @@ -921,7 +941,8 @@ fn as_art_opts( apart: bool, ) -> Option { if let Some(t) = copied_raster_at(n) { - return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n)); + let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart); + return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n)); } let fx = geometry_effects(n); let mut art = match &n.kind { @@ -1016,20 +1037,35 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node { art } -/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the -/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then -/// copied by that Transform effect, each copy an object of its own carrying those raster effects -/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry -/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without -/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, -/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an -/// object of its own ([`copy_leaf`]). -fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node { +/// The art of `n` whose own effects split at `t` ([`copied_raster_at`]): the art the effects before +/// the Transform effect at `t` make of `n`, with their raster effects, then copied by that +/// Transform effect, each copy an object of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry effects after +/// it. The art keeps `n`'s id and carries the raster effects from `t` on, without `n`'s name, +/// visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, each with +/// its raster effects. With `apart`, the Transform effects before `t` make each copy of a path an +/// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through +/// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame +/// and an instance as its symbol's art, whose members take their own geometry effects first +/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art. +fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option) -> Option { let (before, rest) = n.appearance.effects.split_at(t); let mut source = n.clone(); source.appearance.effects = before.to_vec(); let piece = match copied_raster_at(&source) { - Some(at) => copied_raster_art(doc, &source, at, apart), + Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?, + None if needs_outline(&source) => { + let mut art = outlined(&source)?; + if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() { + // The copying Transform effect reshapes what the symbol's members draw. + crate::group::members_as_drawn(doc, &mut art); + } + art.name = None; + art.visible = true; + (art.opacity, art.blend, art.isolate, art.knockout_shape) = (1.0, Default::default(), false, false); + art.extras_mut().mask = None; + art + } None => { let mut art = one_piece(&source); let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc); @@ -1079,11 +1115,12 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> carry.hide_skipped(&mut ran); } art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); - art + Some(art) } /// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect -/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]). +/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster +/// effects listed before it ([`copied_raster_at`]). pub fn outer_effects(n: &Node) -> &[Effect] { match copied_raster_at(n) { Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), @@ -1119,7 +1156,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option return None; } if let Some(t) = copied_raster_at(n) { - return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n)); + return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n)); } if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) { // One element: its pieces never knock each other out. diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 2cf31a9004..d185367f68 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; -use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; +use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; @@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve { shade: flag(p, "shade", true), smooth_shading: true, cap_ends: flag(p, "cap", true), + fill_rule: FillRule::NonZero, curve_samples: None, map_surface: false, } @@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: return Ok(()); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); - paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ())) + paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ())) } /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of @@ -418,7 +419,7 @@ fn cast_surface( None => { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); - caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options) + caster.revolve(path, options.fill_rule, b, options) } } } @@ -449,7 +450,7 @@ fn group_shadow( if !ink.casts() { continue; } - let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; + let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?; cast.push((s.scopes.as_slice(), ink, faces)); } Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) @@ -703,13 +704,16 @@ fn in_order(items: Vec, order: &[usize]) -> Vec { order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect() } -/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and -/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count -/// [`surface`] adds to; its graphics take the symbols of `doc`. +/// A surface of one object about the bounds of `path`, filled with `rule`, built with options +/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast +/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of +/// `doc`. +#[allow(clippy::too_many_arguments)] fn object_surface( doc: Option<&Document>, n: &Node, path: &PathData, + rule: FillRule, fx: &Effect, item: &AppearanceItem, expand: bool, @@ -718,10 +722,16 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast) + surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast) .map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept)) } +/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides +/// leave open the holes `rule` leaves in the profile. +fn rule_options(fx: &Effect, rule: FillRule) -> Revolve { + Revolve { fill_rule: rule, ..fx_options(fx) } +} + /// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of /// that color: across the face with its smooth shading, under colored lights (`colored`) with /// their color. @@ -840,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result, n: &Node) -> Result Result Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect()) } -/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept -/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]). -/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art. -fn wire_art<'a>(id: NodeId, paths: impl IntoIterator, b: Rect, fx: &Effect, options: Revolve) -> Option> { +/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with +/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces +/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge +/// limit, when the canvas draws the source art. +fn wire_art<'a>(id: NodeId, paths: impl IntoIterator, b: Rect, fx: &Effect, options: Revolve) -> Option> { let mut faces = vec![]; - for path in paths { - faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path)); + for (path, rule) in paths { + faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path)); } crate::solids::wireframe::wire_art(id, &faces) } @@ -940,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. - children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?); + children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?); } else { - let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; + let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?; if let Some(b) = path.bounds() - && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()? + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()? { children.push(Arc::new(shadow)); } @@ -970,16 +981,16 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); if crate::solids::renders_wireframe(fx) { - let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?; + let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?; Arc::make_mut(&mut art).appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); children.push(art); continue; } - let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); if let Some(b) = p.bounds() - && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()? + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()? { shadow.appearance.effects = art.appearance.effects.clone(); shadows.push(Arc::new(shadow)); @@ -1127,7 +1138,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let options = shared_options(&shapes, fx_options(fx)).ok()?; if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of every member's faces, with no shadow. - let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path); + let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule)); let mut art = n.clone(); art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false }; art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into(); @@ -1157,6 +1168,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); + let options = Revolve { fill_rule: s.rule, ..options }; let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); @@ -2088,7 +2100,7 @@ mod tests { let mut fx = crate::new_effect(id, &json!({})).unwrap(); fx.params = params.clone(); let n = profile_node(); - let (path, _) = profile(&n).unwrap(); + let (path, rule) = profile(&n).unwrap(); let b = path.bounds().unwrap(); let mut half = n.clone(); if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] { @@ -2096,9 +2108,9 @@ mod tests { } for n in [n, half] { let item = surface_item(&n.appearance.items).unwrap(); - let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); - let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(); - let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(); + let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap(); + let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap(); + let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap(); assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}"); assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); } @@ -2164,11 +2176,11 @@ mod tests { if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] { f.opacity = bad; } - let (path, _) = profile(&n).unwrap(); + let (path, rule) = profile(&n).unwrap(); let b = path.bounds().unwrap(); let item = surface_item(&n.appearance.items).unwrap(); assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow"); - let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); + let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap(); assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn"); assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone"); let shadows = group_shadows(&group(bad)); diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index c4a33a76a2..b61634c844 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1819,11 +1819,24 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() { assert_eq!(ramps, one.iter().skip(1).collect::>(), "the same light ramps"); // The single face's clip holds its seam: the clip reaches past the facet by half the seam. let seam = (face.thickness() / 2.0).clamp(0.05, 0.75); - let widths: Vec = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect(); - assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}"); let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") }; let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap()); - assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}"); + let reaches = |b: Rect| (b.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (b.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1; + assert!(reaches(clip), "{clip:?} {facet:?}"); + // In the composite, the facet over the underlay is one fill of the facet and its seam in each + // channel: no seam stroke of its own, and a path that reaches past the facet by half the seam. + let widths: Vec = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect(); + assert!(widths.is_empty(), "{widths:?}"); + let mut seamed = vec![]; + batch.walk(&mut |n| { + if let [AppearanceItem::Fill(f)] = n.appearance.items.as_slice() + && f.paint != Paint::solid(Color::BLACK) + && f.paint != paint + { + seamed.extend(n.path_data().and_then(PathData::bounds)); + } + }); + assert!(seamed.len() == 3 && seamed.iter().all(|b| reaches(*b)), "{seamed:?} {facet:?}"); } /// `square_node` moved right by `dx`, with id `id` and fill `fill`. diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index 586481d9b5..26399fe162 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -1216,3 +1216,96 @@ fn copies_past_the_budget_each_keep_their_shadow() { assert!(paths > 1 && paths < 1001, "{paths}"); assert_eq!(shadows_in(&art).len(), paths); } + +/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`. +fn type_node(id: u64, effects: Vec) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + n.appearance.effects = effects; + n +} + +/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square +/// centered on its origin. +fn instance(id: u64, effects: Vec) -> (Node, Node) { + let art = Node::path( + NodeId(900), + shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::translate((50.0, 50.0)) }); + n.appearance.effects = effects; + (n, art) +} + +/// Type, an image and a symbol instance with a Transform effect that makes copies give each copy +/// the shadow listed before it, turned and scaled with that copy, the last copy lowest: drawn and +/// expanded. The object paints none around all of them, and a shadow listed after the Transform +/// effect still paints once around them. Built without fonts, type lays out no glyphs and only the +/// image and the instance are checked. +#[test] +fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { + let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + if !fonts { + eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + } + let objects = |effects: Vec| { + let (inst, art) = instance(96, effects.clone()); + let mut out = vec![("image", image(97, effects.clone()), None), ("instance", inst, Some(art))]; + if fonts { + out.push(("type", type_node(95, effects), None)); + } + out + }; + let cases = [ + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]), + ]; + for (params, want, blurs) in cases { + for (kind, n, symbol) in objects(vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]) { + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{kind} {params}"); + let symbol = symbol.as_ref(); + for (how, drawn) in [("drawn", crate::reshape(None, &n, symbol)), ("expanded", expand_outlined(None, &n, symbol))] { + let drawn = drawn.unwrap_or_else(|| panic!("{kind} {params}: {how}")); + assert_eq!(drawn.children().map_or(0, Vec::len), want.len(), "{kind} {params}: {how} copies"); + assert!(drawn.appearance.effects.is_empty(), "{kind} {params}: {how} {:?}", drawn.appearance.effects); + assert!(near(&shadows_in(&drawn), &want), "{kind} {params}: {how} {:?}", shadows_in(&drawn)); + let b = shadow_blurs_in(&drawn); + assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{kind} {params}: {how} blurs {b:?}"); + } + } + } + let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]; + for (kind, n, symbol) in objects(effects) { + assert_eq!(crate::outer_effects(&n).len(), 2, "{kind}"); + let drawn = crate::reshape(None, &n, symbol.as_ref()).unwrap(); + assert!(near(&shadows_in(&drawn), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{kind}: {:?}", shadows_in(&drawn)); + } +} + +/// 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 staying type under one shadow. +#[test] +fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { + if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let n = type_node(99, vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); + let drawn = baked(n); + assert!(near(&shadows_in(&drawn), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&drawn)); +} + +/// Type with a fill whose own geometry effects reshape it keeps one set of raster effects around +/// all the copies. +#[test] +fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() { + let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; + let mut filled = type_node(98, effects.clone()); + filled.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { + effects: vec![fx("path.offsetPath", json!({"offset": 2}))], + ..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)) + })); + assert_eq!(crate::outer_effects(&filled).len(), 2); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ae67281995..e2bc50cdc5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -235,11 +235,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { /// editing and symbol editing mode isolate their own layer, which does not count here; an object /// isolated inside them counts. pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { - st.isolation.filter(|l| { - !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) - && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) - && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) - }) + vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation) } /// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at /// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 6eb21c9a63..f5a51beabb 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Apply as Filter", ["Object", "Plug-ins", "Color Effects"], None, - "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed}", + "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed}", has_selection, filter ), @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Print Ink Fixes", ["Object", "Plug-ins", "Color Effects"], None, - "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", has_doc, print_fixes::run ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Apply Nearest Swatch", ["Object", "Plug-ins", "Color Effects"], None, - "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", + "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", has_selection, nearest::apply ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Apply Fill to Stroke", ["Object", "Plug-ins", "Color Effects"], None, - "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", + "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again, and its axis lines, tick marks and radar rings keep their new rows for every line of their kind. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", has_doc, |s, p| copy_paint(s, p, true) ), @@ -259,7 +259,10 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { // The graph keeps the paint its series marks and labels now have. let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written); let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); - Ok(objects + usize::from(series || labels)) + let painted: Vec = written.iter().map(|(id, _)| *id).collect(); + // A line keeps the paint written to it, also when it already showed it, and the rest stays as its kind keeps it. + let lines = super::super::graph::capture_line_changes(&before, d, &painted) | super::super::graph::capture_line_paint_writes(d, &written); + Ok(objects + usize::from(series || labels || lines)) })?; } // The defaults for new art change the same way, as Swap Fill and Stroke changes them. diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 8a271557a9..9af57f8e02 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,7 +3,7 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths and Trim at Crossings ([`trim`]). +//! into Paths, Trim at Crossings ([`trim`]) and Tangent Circle ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -12,6 +12,7 @@ mod corners; mod effect_tests; mod shape; mod shared_edge; +mod tangent_circle; #[cfg(test)] mod tests; mod trim; @@ -180,6 +181,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(tangent_circle::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/tangent_circle.rs b/crates/engine/src/cmd/addons/pathtools/tangent_circle.rs new file mode 100644 index 0000000000..379f80905b --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangent_circle.rs @@ -0,0 +1,130 @@ +//! Tangent Circle: draw the circles that touch two paths or compound paths at a given radius, or +//! that touch three of them. The geometry is the pathops crate's +//! ([`tangent_circles`](vectorcraft_pathops::addons::pathtools::tangent_circles)). + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, PathData}; +use vectorcraft_pathops::addons::pathtools::{self as pt, TangentCircleError}; + +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, checked_ids_param, cmd, has_selection, index_opt, number_or}; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command. +pub(crate) const COMMAND: &str = "addon.pathtools.tangentCircle"; +/// The undo step's name. +const LABEL: &str = "Tangent Circle"; +/// The radius the command takes with two shapes (pt). +const RADIUS: std::ops::RangeInclusive = 0.01..=1e6; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.tangentCircle", + "Tangent Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (two or three paths or compound paths; default: the selection), radius?: pt 0.01..1000000 (needed with two shapes; three shapes set the radius themselves and take none), circle?: 0..64 (0: every circle found; n: only the nth, the circles listed by radius, then top to bottom, then left to right)} draw the circles that touch two shapes and have the radius, or that touch three shapes. A circle touches a shape when it meets the shape's outline without crossing it, the whole outline lying outside the circle or inside it: it is tangent to the outline at a smooth point and passes through a corner or an open end; the members of a compound path count as one outline. With three shapes, circles up to 64 times the diagonal of the box around the shapes' anchors and handles are found. Each circle is a new ellipse with the current paint on top of the current layer, or of the isolated group (inside an isolated compound path they join it); the circles are selected; one undo step. Locked and hidden shapes given by `ids` are read and left as they are. No circle is an error, and so are more than 64 (shapes touched along a whole curve, such as two concentric circles), an object named twice, shapes at one point or too small for the radius, and more than 2000 segments in all; the document is then unchanged → {ids, found (how many circles touch the shapes)}", + has_selection, + tangent_circle + )] +} + +/// The paths of path or compound path `id`: itself, or its members. +fn paths_of(d: &Document, id: NodeId) -> Result> { + let value = id.0; + let n = d.node(id).ok_or_else(|| bad(COMMAND, format!("no such object id {value}")))?; + match &n.kind { + NodeKind::Path { path, .. } => Ok(vec![path]), + NodeKind::Compound { children, .. } => Ok(children.iter().filter_map(|c| c.path_data()).collect()), + _ => Err(bad(COMMAND, format!("object {value} is not a path or compound path"))), + } +} + +/// The outlines of `ids`, each path's or compound path's subpaths together; counted before they +/// are copied. +fn outlines(d: &Document, ids: &[NodeId]) -> Result> { + let parts = ids.iter().map(|id| paths_of(d, *id)).collect::>>()?; + let segments: usize = parts.iter().flatten().map(|p| pt::tangent_circle_segments(p)).sum(); + if segments > pt::MAX_TANGENT_CIRCLE_SEGMENTS { + return Err(bad(COMMAND, TOO_COMPLEX)); + } + Ok(parts.iter().map(|paths| PathData::new(paths.iter().flat_map(|p| p.subpaths.iter().cloned()).collect())).collect()) +} + +const TOO_COMPLEX: &str = "the shapes are too complex: at most 2000 segments in all"; + +fn tangent_circle(s: &mut Session, p: &Value) -> Result { + // A repeated id is refused before the ids inside another given one are dropped. + if p.get("ids").is_some_and(|v| !v.is_null()) { + let mut seen = HashSet::new(); + if checked_ids_param(s, p, "ids", COMMAND)?.iter().any(|id| !seen.insert(*id)) { + return Err(bad(COMMAND, "`ids` names an object twice")); + } + } + let ids = checked_ids_or_selection(s, p, COMMAND)?; + let d = &s.doc()?.doc; + if !(2..=3).contains(&ids.len()) { + return Err(bad(COMMAND, "select two or three paths or compound paths")); + } + let outlines = outlines(d, &ids)?; + if outlines.iter().any(|o| o.subpaths.iter().all(|sp| sp.anchors.is_empty())) { + return Err(bad(COMMAND, "a shape has no outline")); + } + let given_radius = p.get("radius").is_some_and(|v| !v.is_null()); + let radius = number_or(p, "radius", 0.0, COMMAND)?; + let radius = match (ids.len(), given_radius) { + (2, true) if RADIUS.contains(&radius) => Some(radius), + (2, true) => return Err(bad(COMMAND, "`radius` must be from 0.01 to 1000000 pt")), + (2, false) => return Err(bad(COMMAND, "two shapes need a `radius`")), + (_, true) => return Err(bad(COMMAND, "three shapes set the radius themselves: leave `radius` out")), + (_, false) => None, + }; + let pick = index_opt(p, "circle", COMMAND)?.unwrap_or(0); + if pick > pt::MAX_TANGENT_CIRCLES { + return Err(bad(COMMAND, "`circle` must be from 0 to 64")); + } + let refs: Vec<&PathData> = outlines.iter().collect(); + let found = pt::tangent_circles(&refs, radius).map_err(|e| match e { + // Every outline has points (checked above): all at one place, or too small for the radius. + TangentCircleError::BadInput => bad(COMMAND, "these shapes are too small to measure"), + // The segments were counted above: the search itself went past its limits. + TangentCircleError::TooComplex => bad(COMMAND, "these shapes take too long to search"), + TangentCircleError::TooMany => bad(COMMAND, "more than 64 circles touch these shapes: they may touch along a whole curve"), + })?; + if found.is_empty() { + return Err(bad(COMMAND, "no circle touches these shapes")); + } + let chosen: Vec = match pick { + 0 => found.clone(), + n => match found.get(n - 1) { + Some(c) => vec![*c], + None => { + let found = found.len(); + return Err(bad(COMMAND, format!("`circle` is past the last circle found ({found})"))); + } + }, + }; + // Path art: inside an isolated compound path, the circles join it and take its appearance. + let parent = s.doc()?.target_parent_for_path()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ids = s.edit(LABEL, |d, sel| { + let mut ids = vec![]; + for c in &chosen { + let (r, at) = (c.radius, c.center); + let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) }; + let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(n.id); + d.insert(parent, usize::MAX, n)?; + } + sel.set(ids.iter().copied()); + Ok(ids) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "found": found.len() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangent_circle/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangent_circle/tests.rs new file mode 100644 index 0000000000..9ffc08df52 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangent_circle/tests.rs @@ -0,0 +1,192 @@ +//! Tangent Circle: circles drawn for two shapes and a radius or three shapes, one undo step, the +//! current paint, compound paths, one circle picked, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::Point; + +use super::COMMAND; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn ellipse(s: &mut Session, x: f64, y: f64, w: f64, h: f64, rotation: f64) -> u64 { + let id = s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "rotation": rotation})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + id +} + +fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> u64 { + ellipse(s, cx - r, cy - r, 2.0 * r, 2.0 * r, 0.0) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn count(s: &Session) -> usize { + s.doc().unwrap().doc.layers[0].children().unwrap().len() +} + +/// The circle path `id` is: (center, radius) from its live ellipse. +fn drawn(s: &Session, id: &Value) -> (Point, f64) { + let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not a live shape") }; + let LiveShape::Ellipse { w, h, xf, .. } = live.as_ref() else { panic!("not an ellipse") }; + assert!((w - h).abs() < 1e-9); + (*xf * Point::new(w / 2.0, h / 2.0), w / 2.0) +} + +fn refused(s: &mut Session, p: Value) -> String { + let (steps, objects) = (undo_steps(s), count(s)); + let e = s.execute(COMMAND, &p).unwrap_err().to_string(); + assert_eq!((undo_steps(s), count(s)), (steps, objects), "{p} changed the document"); + e +} + +#[test] +fn two_circles_and_a_radius_draw_every_circle_as_one_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 130.0, 100.0, 10.0); + s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap(); + let steps = undo_steps(&s); + let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 20})).unwrap(); + assert_eq!(r["found"], 6); + let ids = r["ids"].as_array().unwrap().clone(); + assert_eq!(ids.len(), 6); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(count(&s), 8); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 6); + let fill = st.doc.node(NodeId(ids[0].as_u64().unwrap())).unwrap().appearance.fill_paint(); + assert_eq!(fill, s.paint.fill); + // Outside both: 30 from each center, at x = 115. + let h = (900.0f64 - 225.0).sqrt(); + let centers: Vec<(Point, f64)> = ids.iter().map(|id| drawn(&s, id)).collect(); + for want in [Point::new(115.0, 100.0 - h), Point::new(115.0, 100.0 + h)] { + // Within the Bézier circles' own error (0.0273% of the radius) of the ideal answer. + assert!(centers.iter().any(|(c, r)| (*c - want).hypot() < 0.02 && (r - 20.0).abs() < 1e-9), "{centers:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(count(&s), 2); +} + +#[test] +fn three_circles_and_one_picked() { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 10.0), circle(&mut s, 180.0, 100.0, 10.0), circle(&mut s, 100.0, 160.0, 10.0)]; + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // The selection: all eight, smallest first; the first is the one outside all three, about the + // circumcenter (140, 130), 50 from each center. + let r = s.execute(COMMAND, &json!({"circle": 1})).unwrap(); + assert_eq!(r["found"], 8); + let one = r["ids"].as_array().unwrap(); + assert_eq!(one.len(), 1); + let (c, radius) = drawn(&s, &one[0]); + assert!((c - Point::new(140.0, 130.0)).hypot() < 0.05 && (radius - 40.0).abs() < 0.05, "{c:?} {radius}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert_eq!(s.execute(COMMAND, &json!({})).unwrap()["ids"].as_array().unwrap().len(), 8); + assert!(refused(&mut s, json!({"ids": ids, "circle": 9})).contains("past the last circle found (8)")); +} + +#[test] +fn compound_rotated_and_locked_shapes() { + let mut s = session(); + // A ring as a compound path, and an ellipse turned 30° inside its hole. + let outer = circle(&mut s, 200.0, 150.0, 80.0); + let inner = circle(&mut s, 200.0, 150.0, 60.0); + s.execute("select.set", &json!({"ids": [outer, inner]})).unwrap(); + let ring = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let oval = ellipse(&mut s, 180.0, 140.0, 40.0, 20.0, 30.0); + s.execute("select.set", &json!({"ids": [oval]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [ring]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"ids": [ring, oval], "radius": 22})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + // In the hole, 38 from the center, and 22 from the oval (reaching 42 along its long axis and + // 32 along its short one): two by each end of the oval. + assert_eq!(ids.len(), 4, "{r}"); + for id in ids { + let (c, radius) = drawn(&s, id); + assert!(((c - Point::new(200.0, 150.0)).hypot() - (60.0 - radius)).abs() < 0.05, "{c:?}"); + } + // The locked oval and the hidden ring were read and left as they were. + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(oval)).unwrap().locked); + assert!(!d.node(NodeId(ring)).unwrap().visible); +} + +#[test] +fn circles_go_into_an_isolated_group() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 130.0, 100.0, 10.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 5})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(id), Some(NodeId(group))); + // On top of the group's art. + assert_eq!(d.node(NodeId(group)).unwrap().children().unwrap().last().map(|n| n.id), Some(id)); +} + +#[test] +fn circles_join_an_isolated_compound_path() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 130.0, 100.0, 10.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": compound})).unwrap(); + let members: Vec = s.doc().unwrap().doc.node(NodeId(compound)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect(); + let r = s.execute(COMMAND, &json!({"ids": members, "radius": 5})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(NodeId(compound))); + // A compound path and one of its own members are taken as the compound path alone: one shape. + let e = refused(&mut s, json!({"ids": [compound, members[0]], "radius": 5})); + assert!(e.contains("two or three"), "{e}"); + // A repeated member is refused even though the compound path holds it. + let other = circle(&mut s, 300.0, 100.0, 10.0); + let e = refused(&mut s, json!({"ids": [compound, members[0], members[0], other], "radius": 5})); + assert!(e.contains("twice"), "{e}"); +} + +#[test] +fn errors_leave_the_document_unchanged() { + let mut s = session(); + let a = circle(&mut s, 50.0, 50.0, 10.0); + let b = circle(&mut s, 250.0, 50.0, 10.0); + let c = circle(&mut s, 150.0, 200.0, 10.0); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 5})).contains("no circle touches")); + assert!(refused(&mut s, json!({"ids": [a, b]})).contains("need a `radius`")); + assert!(refused(&mut s, json!({"ids": [a, b, c], "radius": 5})).contains("leave `radius` out")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 0})).contains("0.01")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": "5 mm"})).contains("must be a number")); + assert!(refused(&mut s, json!({"ids": [a], "radius": 5})).contains("two or three")); + assert!(refused(&mut s, json!({"ids": [a, a], "radius": 5})).contains("twice")); + let e = refused(&mut s, json!({"ids": [a, a as f64], "radius": 5})); + assert!(e.contains("not a non-negative integer"), "{e}"); + // Two lone anchors at one place. + let dot = |s: &mut Session| s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap(); + let (p, q) = (dot(&mut s), dot(&mut s)); + assert!(refused(&mut s, json!({"ids": [p, q], "radius": 5})).contains("too small to measure")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": 65})).contains("from 0 to 64")); + assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": -1})).contains("whole number")); + let t = s.execute("text.create", &json!({"x": 10, "y": 280, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + assert!(refused(&mut s, json!({"ids": [a, t], "radius": 5})).contains("not a path")); + let anchors: Vec = (0..2002).map(|i| json!({"x": i as f64 * 0.1, "y": 250.0 + (i % 2) as f64})).collect(); + let zigzag = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + assert!(refused(&mut s, json!({"ids": [a, zigzag], "radius": 5})).contains("at most 2000 segments")); + // Concentric circles touched all the way round. + let inner = circle(&mut s, 50.0, 50.0, 40.0); + assert!(refused(&mut s, json!({"ids": [a, inner], "radius": 15})).contains("whole curve")); +} diff --git a/crates/engine/src/cmd/addons/pathtools/trim.rs b/crates/engine/src/cmd/addons/pathtools/trim.rs index 134edc6607..f1ffab9ba0 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim.rs @@ -1,15 +1,13 @@ //! Trim at Crossings: remove the stretch of a path between the places where other paths, or the //! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle //! touches, or every stretch a line through some points crosses. It works on every path that can -//! be edited, selected or not. - -use std::collections::HashSet; +//! be edited, selected or not. What it removes is worked out by +//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeId, NodeKind}; -use vectorcraft_geom::kurbo::{Line, PathSeg}; -use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit}; -use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::addons::trim::plan::{self, Limits, Pick, Stretches}; use super::super::super::draw2::replace_with_pieces; use super::super::super::pathops::Beside; @@ -41,16 +39,6 @@ pub(super) fn specs() -> Vec { )] } -/// What picks the stretches to remove. -enum Pick { - /// The stretch of the nearest path within the tolerance of the point. - At(Point, f64), - /// Every stretch the rectangle touches. - Rect(Rect), - /// Every stretch the line through the points crosses. - Line(Vec, Rect), -} - fn pick(p: &Value) -> Result { const C: &str = "addon.pathtools.trim"; let given = |key: &str| p.get(key).filter(|v| !v.is_null()); @@ -89,194 +77,15 @@ fn pick(p: &Value) -> Result { } } -/// A path that takes part: its id, geometry and control-point box. -type Part<'a> = (NodeId, &'a PathData, Rect); - -/// The paths that take part, bottom to top: the ones that can be edited, without guides and -/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the -/// members of a compound clipping path included. -fn parts(d: &Document) -> Vec> { - let editable = d.editable(); - let mut masks = HashSet::new(); - d.walk(|n| { - if n.clips() - && let Some(first) = n.children().and_then(|c| c.first()) - { - first.walk(&mut |m| { - masks.insert(m.id); - }); - } - }); - let mut out = vec![]; - d.walk(|n| { - if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind - && !masks.contains(&n.id) - && let Some(b) = path.control_bounds() - && editable(n.id) - { - out.push((n.id, path, b)); - } - }); - out -} - -/// Most box tests one command makes between a line's pieces and the paths' segments. -const MAX_LINE_TESTS: usize = 60_000_000; -/// Most tests one command makes between the boxes of the paths to trim and of the other paths. -const MAX_BOX_TESTS: usize = 50_000_000; - -/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`; -/// `None` once it is spent. -fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option { - let segs: Vec<_> = (0..sp.segment_count()) - .map(|i| { - let c = sp.segment(i); - (c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9)) - }) - .collect(); - let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) }; - for w in pts.windows(2) { - let [a, b] = w else { continue }; - let piece = Rect::from_points(*a, *b); - *budget = budget.checked_sub(1)?; - if !reach.overlaps(piece) { - continue; - } - for (c, r) in &segs { - *budget = budget.checked_sub(1)?; - if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() { - return Some(true); - } - } - } - Some(false) -} - -/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`. -fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result { - match pick { - Pick::At(..) => Ok(false), - Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)), - Pick::Line(pts, _) => crossed_by_line(piece, pts, budget) - .ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")), - } -} - -/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths -/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no -/// part of `path` leaves it out before its crossings are looked for. -fn trimmed( - path: &PathData, - others: &[&PathData], - pick: &Pick, - on: Option, - budget: &mut usize, - work: &mut pt::Work, -) -> Result, usize)>> { - const C: &str = "addon.pathtools.trim"; - let reached = match pick { - Pick::At(..) => true, - Pick::Rect(r) => hit::intersects_rect(path, *r), - Pick::Line(..) => { - let mut any = false; - for sp in &path.subpaths { - if touches(sp, pick, budget)? { - any = true; - break; - } - } - any - } - }; - if !reached { - return Ok(None); - } - let places = - pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?; - let mut subs = vec![]; - let mut removed = 0; - for (si, sp) in path.subpaths.iter().enumerate() { - // The places come in subpath order: this subpath's are one run of them. - let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si); - let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect(); - let spans = pt::spans(sp, &here); - let marks: Vec = match pick { - Pick::At(..) => { - let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t)); - (0..spans.len()).map(|i| Some(i) == at).collect() - } - _ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::>()?, - }; - match pt::without_spans(sp, &spans, &marks) { - Some(pieces) => { - removed += marks.iter().filter(|m| **m).count(); - subs.extend(pieces); - } - None => subs.push(sp.clone()), - } - } - Ok((removed > 0).then_some((subs, removed))) -} - fn trim(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.pathtools.trim"; let pick = pick(p)?; let st = s.doc()?; - let d = &st.doc; - let parts = parts(d); // In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them. let root = crate::cmd::ordinary_isolation(st); - let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id)); - // The paths to trim, each with the place `at` falls on. - let targets: Vec<(usize, Option)> = match &pick { - Pick::At(at, tolerance) => { - let mut best: Option<(usize, pt::Place, f64)> = None; - for (i, (id, path, b)) in parts.iter().enumerate() { - if !in_scope(*id) { - continue; - } - let b = b.inflate(*tolerance, *tolerance); - if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) { - continue; - } - // Of paths equally near, the one on top. - if let Some((si, seg, t, _, dist)) = path.nearest(*at) - && dist <= *tolerance - && best.is_none_or(|b| dist <= b.2) - { - best = Some((i, (si, seg, t), dist)); - } - } - best.map(|(i, on, _)| (i, Some(on))).into_iter().collect() - } - Pick::Rect(r) | Pick::Line(_, r) => { - parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect() - } - }; - // Each path to trim has its box tested against every other path's. - if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS { - return Err(bad(C, "the rectangle or line reaches too many paths to check")); - } - let mut plan: Vec<(NodeId, Vec)> = vec![]; - let mut removed = 0; - let mut budget = MAX_LINE_TESTS; - // One budget of crossing work for every path the command trims. - let mut work = pt::Work::default(); - for (i, on) in targets { - let Some((id, path, b)) = parts.get(i) else { continue }; - let reach = b.inflate(1e-3, 1e-3); - let others: Vec<&PathData> = - parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect(); - let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue }; - removed += n; - // A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths. - let pieces = match (path.subpaths.len(), subs.is_empty()) { - (_, true) => vec![], - (1, false) => subs.into_iter().map(PathData::single).collect(), - _ => vec![PathData::new(subs)], - }; - plan.push((*id, pieces)); - } + let trimmed = plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).map_err(|e| bad(C, e.message()))?; + let removed: usize = trimmed.iter().map(|t| t.count).sum(); + let plan: Vec<(NodeId, Vec<_>)> = trimmed.into_iter().map(|t| (t.id, t.pieces)).collect(); if plan.is_empty() { return Ok(json!({ "ids": [], "removed": 0 })); } diff --git a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs index 42adb70ab9..a36c705e4f 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs @@ -480,6 +480,129 @@ fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() { assert_eq!(steps(&s), n + 2); } +/// The ends of each red path the tool shows. +fn highlighted(s: &mut Session, view: crate::ViewInfo) -> Vec<(Point, Point)> { + use vectorcraft_geom::kurbo::ParamCurve; + s.overlays(view) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => { + let segs: Vec<_> = path.segments().collect(); + Some((segs.first()?.start(), segs.last()?.end())) + } + _ => None, + }) + .collect() +} + +#[test] +fn hovering_with_the_tool_shows_the_stretch_its_click_removes() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let (h, _, _) = across_and_uprights(&mut s); + let hidden = line(&mut s, &[(0.0, 200.0), (300.0, 200.0)], false); + set_flags(&mut s, hidden, false, false); + let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() }; + s.select_tool("trimAtCrossings", view).unwrap(); + let n = steps(&s); + // Over the middle of the line across: the stretch between the uprights, and nothing changes. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap(); + let shown = highlighted(&mut s, view); + assert!(matches!(shown.as_slice(), [(a, b)] if near(*a, 100.0, 100.0) && near(*b, 200.0, 100.0)), "{shown:?}"); + assert_eq!(steps(&s), n); + // Over the hidden path and over empty canvas: nothing. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 200.0), view).unwrap(); + assert!(highlighted(&mut s, view).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 250.0), view).unwrap(); + assert!(highlighted(&mut s, view).is_empty()); + // A click where the stretch was shown removes exactly it: the line keeps 0 to 100 and 200 to 300. + s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 101.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 101.0), view).unwrap(); + assert_eq!(steps(&s), n + 1); + assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 100.0, 100.0)); + let rest = stack(&s).into_iter().find(|id| *id != h && path(&s, *id).subpaths.len() == 1 && near(ends(&s, *id).0, 200.0, 100.0)); + assert!(rest.is_some_and(|id| near(ends(&s, id).1, 300.0, 100.0))); + assert!(highlighted(&mut s, view).is_empty(), "the edit drops the highlight"); +} + +/// The red paths the tool shows. +fn red(s: &mut Session, view: crate::ViewInfo) -> Vec { + s.overlays(view) + .into_iter() + .filter_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => Some(path), + _ => None, + }) + .collect() +} + +/// The length of every path in the first layer. +fn total_length(s: &Session) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArclen; + stack(s).into_iter().flat_map(|id| path(s, id).to_bezpath().segments().collect::>()).map(|seg| seg.arclen(1e-9)).sum() +} + +/// `act` removes exactly the red paths shown before it: the paths lose their length, and nothing +/// is left on the middle of any of them. +fn removes_what_was_shown(s: &mut Session, view: crate::ViewInfo, act: &dyn Fn(&mut Session)) { + use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen}; + let shown = red(s, view); + assert!(!shown.is_empty()); + let shown_length: f64 = shown.iter().flat_map(|p| p.segments().collect::>()).map(|seg| seg.arclen(1e-9)).sum(); + let before = total_length(s); + act(s); + assert!((before - total_length(s) - shown_length).abs() < 1e-3, "{before} - {} != {shown_length}", total_length(s)); + for p in &shown { + let segs: Vec<_> = p.segments().collect(); + let mid = segs[segs.len() / 2].eval(if segs.len() % 2 == 1 { 0.5 } else { 0.0 }); + let left = stack(s).into_iter().filter_map(|id| path(s, id).nearest(mid)).map(|n| n.4).fold(f64::INFINITY, f64::min); + assert!(left > 0.5, "a path is left at {mid:?}"); + } +} + +#[test] +fn what_the_tool_shows_before_a_click_or_a_release_is_what_the_command_removes() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() }; + let ev = |kind, x, y| PointerEvent::new(kind, x, y); + let alt = Mods { alt: true, ..Mods::default() }; + let setup = || { + let mut s = session(); + s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + line(&mut s, &[(50.0, 100.0), (350.0, 100.0)], false); + // A Z whose first and last sides cross. + line(&mut s, &[(0.0, 160.0), (100.0, 260.0), (100.0, 160.0), (0.0, 260.0)], false); + s.select_tool("trimAtCrossings", view).unwrap(); + s + }; + // A click on the ellipse's top, on the line inside it and on the Z's loop. + for (x, y) in [(200.0, 51.0), (200.0, 101.0), (101.0, 210.0)] { + let mut s = setup(); + s.pointer(&ev(PointerKind::Move, x, y), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Down, x, y), view).unwrap(); + s.pointer(&ev(PointerKind::Up, x, y), view).unwrap(); + }); + } + // A rectangle over the ellipse's left side and the line. + let mut s = setup(); + s.pointer(&ev(PointerKind::Down, 90.0, 90.0), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 120.0, 110.0), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Up, 120.0, 110.0), view).unwrap(); + }); + // An Alt line through the ellipse's bottom and the Z's tail. + let mut s = setup(); + s.pointer(&ev(PointerKind::Down, 200.0, 140.0).with_mods(alt), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 200.0, 170.0).with_mods(alt), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, 10.0, 250.0).with_mods(alt), view).unwrap(); + removes_what_was_shown(&mut s, view, &|s| { + s.pointer(&ev(PointerKind::Up, 10.0, 250.0).with_mods(alt), view).unwrap(); + }); +} + #[test] fn a_line_too_long_to_check_against_the_paths_is_refused() { let mut s = session(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 04a36e556f..84596eb53c 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, false) ), @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, clear_appearance ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, reduce_basic ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the paint, weight, opacity and blend mode it writes to the line's topmost visible row)", has_doc, set_item ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, remove_item ), @@ -111,7 +111,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, duplicate_item ), @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; moving rows of such a group whose members' rows differ is an error), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", has_doc, copy_from ), @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {ids}", has_doc, show_all_hidden ), @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Move Appearance", [], None, - "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}", + "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}", has_doc, transfer ), @@ -538,7 +538,8 @@ pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec { } /// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside -/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: +/// it, and each such Axes or Legend group of a graph by the lines and labels directly inside it +/// ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: /// the Appearance panel lists those rows and edits them by index. pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec { super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty()) @@ -559,8 +560,9 @@ fn holds_no_look(group: &Node) -> bool { } /// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own -/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or -/// another attribute of its own is read itself, with that attribute. +/// ([`holds_no_look`]) gives the paths directly inside it, backmost first, and such an Axes or Legend group of a graph +/// the lines and labels directly inside it. A series group with an effect, an opacity or another attribute of its own is +/// read itself, with that attribute. fn look_holders(d: &Document, id: NodeId) -> Vec { super::graph::series_group_marks_where(d, &[id], holds_no_look) } @@ -626,11 +628,48 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { Ok(ids) } +/// Refuse a row index given a graph's Axes or Legend group that stands for lines and labels whose stacks differ +/// ([`rowless_series_marks`]), unless the index is `aligned`, a row of the backmost one's stack: the same index names a +/// different row in each of them. +pub(crate) fn check_part_rows(s: &Session, p: &Value, aligned: bool, cmd: &str) -> Result<()> { + if aligned { + return Ok(()); + } + let d = &s.doc()?.doc; + for id in appearance_targets(s, p)? { + let Some(n) = d.node(id).filter(|n| n.appearance.items.is_empty()) else { continue }; + if let Some(members) = super::graph::graph_part_members(d, n) + && appearances_differ(d, &members) + { + return Err(bad( + cmd, + format!("the lines and labels in graph group {} have different appearance rows: pass `aligned: true` or their ids", id.0), + )); + } + } + Ok(()) +} + +/// Whether row `index` of `n` is the topmost visible row of its kind, the row a graph keeps for a label or line. +fn is_top_shown(n: &Node, index: usize) -> bool { + let items = &n.appearance.items; + items.get(index).is_some_and(|it| items.iter().rposition(|o| o.is_fill() == it.is_fill() && o.visible()) == Some(index)) +} + +/// `ids` without the objects whose topmost visible fill and stroke rows ([`super::graph::label_rows`]) an edit left as +/// they were (`before`: the document before it), unless `wrote` says the edit wrote one of those rows. An edit of a +/// hidden row of a graph label or line then leaves what the graph keeps for its kind as it is. +fn shown_rows_edited(before: &Document, d: &Document, ids: Vec, wrote: impl Fn(NodeId) -> bool) -> Vec { + let shown = |doc: &Document, id: NodeId| doc.node(id).map(super::graph::label_rows); + ids.into_iter().filter(|id| wrote(*id) || shown(before, *id) != shown(d, *id)).collect() +} + /// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters). /// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the /// rows and characters of graph labels, is stored on their graphs in the same step -/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not +/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]), and so are the rows of +/// the graph lines it reaches ([`super::graph::capture_line_changes`]). Nothing targeted is not /// an edit, and when `f` leaves every target as it was, the document and its undo history stay as /// they are. /// @@ -652,7 +691,7 @@ pub(crate) fn edit_items( edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| { let series = capture_series_changes(before, d, edited); // The rows `f` edited are kept by `edit_items_then`. - let labels = super::graph::capture_label_changes(before, d, edited, false); + let labels = super::graph::capture_label_changes(before, d, edited, false, None); Ok(series || labels) }) } @@ -670,6 +709,45 @@ pub(crate) fn edit_items_then( cmd: &str, label: &str, fill: bool, + f: impl FnMut(&mut Node, Option) -> Result<()>, + after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, +) -> Result> { + edit_items_writing_then(s, ids, item, of, cmd, label, fill, super::graph::RowWrites::NONE, f, after) +} + +/// [`edit_items`] for an edit that writes the attributes `writes` says to the row of each target it edits: a graph line +/// keeps them for its kind when that row is its topmost visible one, also when the line already showed them +/// ([`super::graph::capture_line_row_writes`]). +#[allow(clippy::too_many_arguments)] +pub(crate) fn edit_items_writing( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + of: Option, + cmd: &str, + label: &str, + fill: bool, + writes: super::graph::RowWrites, + f: impl FnMut(&mut Node, Option) -> Result<()>, +) -> Result> { + edit_items_writing_then(s, ids, item, of, cmd, label, fill, writes, f, |before, d, edited| { + let series = capture_series_changes(before, d, edited); + let labels = super::graph::capture_label_changes(before, d, edited, false, None); + Ok(series || labels) + }) +} + +/// [`edit_items_then`] with the attributes `writes` says, as [`edit_items_writing`] keeps them. +#[allow(clippy::too_many_arguments)] +fn edit_items_writing_then( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + of: Option, + cmd: &str, + label: &str, + fill: bool, + writes: super::graph::RowWrites, mut f: impl FnMut(&mut Node, Option) -> Result<()>, mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, ) -> Result> { @@ -693,6 +771,10 @@ pub(crate) fn edit_items_then( let mut edited = Vec::new(); // The objects whose rows `f` edited: on type, no row means its characters. let mut rows = Vec::new(); + // The objects where `f` wrote the topmost visible row of its kind. + let mut wrote = Vec::new(); + // The row of each object `f` wrote: its index, else the topmost row of the kind. + let mut written = Vec::new(); for (id, item) in ids.iter().zip(&per) { let Some(item) = item else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -702,10 +784,22 @@ pub(crate) fn edit_items_then( if index.is_some() { rows.push(*id); } + if index.is_none_or(|i| is_top_shown(n, i)) { + wrote.push(*id); + } + written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at))); } let more = after(&before, d, &edited)?; - let labels = super::graph::capture_label_rows(d, &rows); - Ok(count_changed(d, &before, &edited) + usize::from(more || labels)) + // A graph line keeps only the attributes of its rows that the edit changed, and those it wrote (`writes`): the + // others stay as its kind keeps them, which the line may not show yet. + rows.retain(|id| !super::graph::is_graph_line(d, *id)); + let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, rows, |id| wrote.contains(&id))); + let mut lines = super::graph::capture_line_changes(&before, d, &edited); + if writes != super::graph::RowWrites::NONE { + let (on_fill, on_stroke) = if fill { (writes, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, writes) }; + lines |= super::graph::capture_line_row_writes(d, &written, on_fill, on_stroke); + } + Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines)) })?; Ok(aimed) } @@ -716,6 +810,17 @@ pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option, id ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?))) } +/// Keep the object rows of the graph labels among `ids` for every label of their kind +/// ([`super::graph::capture_label_rows`]), and of the graph lines among them only the attributes the edit changed +/// ([`super::graph::capture_line_changes`]): a line's other attributes stay as its kind keeps them, which the line may +/// not show yet. Returns whether what a graph keeps changed. +fn capture_row_edits(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool { + let labels: Vec = ids.iter().copied().filter(|id| !super::graph::is_graph_line(d, *id)).collect(); + let labels = super::graph::capture_label_rows(d, &labels); + let lines = super::graph::capture_line_changes(before, d, ids); + labels || lines +} + /// How many of `ids` differ in `d` from `before`. pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_doc::Document, ids: &[NodeId]) -> usize { ids.iter().filter(|id| d.node(**id) != before.node(**id)).count() @@ -854,10 +959,13 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let lines: Vec = added.iter().map(|(id, _)| *id).collect(); let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + capture_row_edits(&before, d, &ids); + // A graph line keeps the row it got for its kind, also when it showed that row's paint, weight and transparency. + super::graph::capture_line_kind_rows(d, &lines, (fill, !fill), false); Ok(()) })?; // A fill added above the active row becomes the active row; otherwise the rows above the new @@ -1046,7 +1154,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { let mut targets: Vec = marks.iter().copied().filter(|id| !within.contains(id)).collect(); if targets.is_empty() { if stands { - return Err(bad(C, "`source` is the only path in series group `target`")); + return Err(bad(C, "`source` is the only path, line or label that graph group `target` stands for")); } targets.push(target); } @@ -1091,8 +1199,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result { rows.extend(painted_rows(d, both_kinds(&targets))); let painted = super::graph::capture_series_top_paints(d, &rows); let object = super::graph::capture_series_object_opacity(d, &changed); - // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. - let labels = super::graph::capture_label_rows(d, &changed); + // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. Graph lines are + // taken in paint order, so the targets are captured again on their own, after a cleared source in front of them. + let labels = super::graph::capture_label_rows(d, &changed) | super::graph::capture_label_rows(d, &targets); let all: Vec = from.iter().chain(&targets).chain(&group).copied().collect(); Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot)) })?; @@ -1150,7 +1259,7 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &ids); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; s.active_appearance_item = None; @@ -1167,6 +1276,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad("appearance.setItem", "select objects or give ids")); } + check_part_rows(s, p, aligned(p, "appearance.setItem")?, "appearance.setItem")?; let blend = str_param(p, "blend").and_then(BlendMode::parse); // When every object comes out as it was (for example, when none has item `index`), the document // and its undo history stay as they are. @@ -1175,6 +1285,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let per = rows_per_target(&before, of, &ids, &[idx], aligned(p, "appearance.setItem")?); super::overprint::edit_counted(s, "Appearance", |d| { let mut edited = Vec::new(); + // The targets that have the row: an aligned row leaves out the members of a graph's Axes or Legend group that + // lack it, and the graph keeps the rows of the labels and lines it reached only. + let mut reached = Vec::new(); for (id, at) in ids.iter().zip(&per) { let Some(&idx) = at.first() else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -1185,6 +1298,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { } let bounds = n.geometric_bounds(); let Some(item) = n.appearance.items.get_mut(idx) else { continue }; + reached.push(*id); let (pp, op, bl, vis, bounds) = match item { AppearanceItem::Fill(f) => (&mut f.paint, &mut f.opacity, &mut f.blend, &mut f.visible, bounds), AppearanceItem::Stroke(st) => { @@ -1227,8 +1341,19 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let labels = super::graph::capture_label_rows(d, &ids); - Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) + let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); + let labels = capture_row_edits(&before, d, &reached); + // A graph line keeps what was written to its topmost visible row, also when it already showed it. + let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect(); + // Only the values the edit applied: a null weight or opacity leaves the row as it is. + let writes = super::graph::RowWrites { + paint: paint.is_some(), + weight: p.get("weight").and_then(Value::as_f64).is_some(), + opacity: p.get("opacity").and_then(Value::as_f64).is_some(), + blend: blend.is_some(), + }; + let lines = super::graph::capture_line_row_writes(d, &tops, super::graph::RowWrites { weight: false, ..writes }, writes); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels || lines)) })?; if let Some(pa) = &paint { s.remember_paint(pa); @@ -1256,14 +1381,20 @@ pub(super) fn item_indices(p: &Value, cmd: &str) -> Result> { fn remove_item(s: &mut Session, p: &Value) -> Result { let idx = item_indices(p, "appearance.removeItem")?; let ids = require_targets(s, p, "appearance.removeItem")?; + check_part_rows(s, p, aligned(p, "appearance.removeItem")?, "appearance.removeItem")?; // When no object has an item at any of the indices, the document and its undo history stay as // they are. let before = s.doc()?.doc.clone(); let of = design_reference(s, p, "appearance.removeItem")?; let per = rows_per_target(&before, of, &ids, &idx, aligned(p, "appearance.removeItem")?); super::overprint::edit_counted(s, "Remove Item", |d| { + // The targets that had a row to remove, as in `set_item`. + let mut reached = Vec::new(); for (id, idx) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { + if idx.iter().any(|i| *i < n.appearance.items.len()) { + reached.push(*id); + } let mut idx = idx.clone(); idx.sort_unstable(); // From the top down, so the lower indices stay valid. @@ -1275,7 +1406,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |_| false)); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The rows removed from the active row's object, which need not come first in `ids`. @@ -1295,6 +1426,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`contents` goes with `to`")); } let ids = require_targets(s, p, C)?; + check_part_rows(s, p, aligned(p, C)?, C)?; // Where the first target's copy landed, and where it landed on the active row's object (the // first selected one, not always the first target): copies placed at `to` land at a different // index on stacks of other lengths. @@ -1319,6 +1451,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { // Copies that became the topmost visible row of their kind: the series stores their paint even when the object // showed it. let mut added = Vec::new(); + // The targets that took a copy, as in `set_item`. + let mut reached = Vec::new(); for (id, idx) in ids.iter().zip(&per) { let Some(n) = d.node_mut(*id) else { continue }; let has_contents = n.contents_label().is_some(); @@ -1343,6 +1477,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { ap.set_contents_at(c); } any = true; + reached.push(*id); continue; } let mut idx = idx.clone(); @@ -1357,6 +1492,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { added.push((*id, kind)); } any = true; + if reached.last() != Some(id) { + reached.push(*id); + } } } } @@ -1365,9 +1503,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let mut rows = top_paint_changed(&before, d, &ids); + let top_copies: Vec = added.iter().map(|(id, _)| *id).collect(); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id))); Ok(()) })?; // Rows at or above each copy move up by one (by the block, for copies placed at `to`). @@ -1407,7 +1546,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown)); super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown)); - super::graph::capture_label_rows(d, &shown); + capture_row_edits(&before, d, &shown); Ok(shown) })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) @@ -1431,6 +1570,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { return move_contents(s, &ids, to); } let ids = require_targets(s, p, C)?; + check_part_rows(s, p, aligned, C)?; // Where an aligned row would go in each of several different stacks isn't one place. if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) { return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); @@ -1457,7 +1597,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = super::graph::capture_label_changes(&before, d, &ids, true, None); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The moved row stays the active one; the rows it passed shift by one. @@ -1503,7 +1643,7 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result Result { slot.get_or_insert(n.appearance.contents_at()); } slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?; - // A graph label's kind keeps where its rows paint relative to the characters. - let labels = super::graph::capture_label_rows(d, ids); + // A graph label's kind keeps where its rows paint relative to the characters, from the labels the move changed. + let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, ids.to_vec(), |_| false)); Ok(count_changed(d, &before, ids) + usize::from(labels)) })?; Ok(json!({ "contents": slot })) @@ -1804,15 +1944,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { let object = super::graph::capture_series_object_opacity(d, &objects); // Graph labels keep their new rows, characters and paragraphs per kind of label. // On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other - // attributes go to the characters. + // attributes go to the characters. Without a transparency pick, the object opacity and blend mode a kind keeps stay, + // also when the label or line picked onto still shows other ones until the graph is drawn again. `append` keeps + // only the kinds of row it added; a row of the other kind stays as the kind keeps it. + let transparency = attrs.appearance.transparency; let rows = if append { - super::graph::capture_label_rows(d, &targets) + super::graph::capture_label_kind_rows(d, &targets, paints, transparency) } else { - attrs.appearance.transparency && super::graph::capture_label_object_opacity(d, &targets) + transparency && super::graph::capture_label_object_opacity(d, &targets) }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; - Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text)) + // A graph line is a path: a whole pick and `append` write its rows. A pick of some attributes keeps those it + // changed, and the rest stay as its kind keeps them, which the line may not show yet. Row attributes the graph + // does not keep (overprint, caps, joins, miter limit, dashes) leave what its kind keeps as it is. + let lines = match (rows_written, transparency) { + _ if append => super::graph::capture_line_kind_rows(d, &targets, paints, transparency), + (true, true) => super::graph::capture_line_rows(d, &targets), + (true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets), + (false, _) => { + // The topmost row of each kind, which the pick wrote: what it wrote is kept also when the line showed it. + let tops: Vec<(NodeId, usize)> = targets + .iter() + .filter_map(|id| d.node(*id).map(|n| (*id, &n.appearance.items))) + .flat_map(|(id, items)| { + [true, false].into_iter().filter_map(move |kind| items.iter().rposition(|it| it.is_fill() == kind).map(|at| (id, at))) + }) + .collect(); + // A transparency pick applies the row's opacity and blend mode together. + let on_fill = super::graph::RowWrites { paint: fill.color, weight: false, opacity: opacities.0, blend: opacities.0 }; + let on_stroke = super::graph::RowWrites { + paint: stroke.color, + weight: stroke.weight && source_has(false), + opacity: opacities.1, + blend: opacities.1, + }; + super::graph::capture_line_changes(&before, d, &targets) | super::graph::capture_line_row_writes(d, &tops, on_fill, on_stroke) + } + }; + Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; Ok(finish(s, &targets)) } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 01537c7b68..98aa9ae490 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 2eb81eaef5..203fd62338 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -23,20 +23,30 @@ fn is_trace_group(n: &Node) -> bool { && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } -/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]). +/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; -/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths -/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto -/// Grouping groups hold filled paths.) +/// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose +/// members after the clipping path are all stroked paths without fills, or all filled paths +/// without strokes (the strokes' outlines, on a stretched image), so that it is still found after +/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made +/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one +/// of stroked paths without fills. (Auto Grouping groups hold filled paths.) fn is_seam_fills(n: &Node) -> bool { - let stroke_only = |m: &Arc| { - matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) - && m.appearance.fill_paint() == Paint::None - && m.appearance.stroke_paint() != Paint::None - }; - matches!(n.kind, NodeKind::Group { clip: false, .. }) - && (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only))) + let path = |m: &Arc| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; + let fill_only = |m: &Arc| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None; + let named = n.name.as_deref() == Some(SEAM_FILLS_NAME); + match &n.kind { + NodeKind::Group { clip: true, children } => { + named + || children + .split_first() + .is_some_and(|(_, members)| !members.is_empty() && (members.iter().all(stroke_only) || members.iter().all(fill_only))) + } + NodeKind::Group { clip: false, children } => named || (!children.is_empty() && children.iter().all(stroke_only)), + _ => false, + } } const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; @@ -411,7 +421,8 @@ fn by_color_param(cmd: &str, p: &Value) -> Result { /// starts another group of that paint, which keeps the stacking order of those items. Items /// farther apart can still share antialiased pixels at small view or raster-export scales, so /// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is, -/// under every other group. Any other group among `items` (Auto Grouping) is refused. +/// under every other group; above another item it is refused. Any other group among `items` (Auto +/// Grouping) is refused. fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result>> { use std::collections::{BTreeMap, HashMap}; use std::ops::Bound::{Excluded, Unbounded}; @@ -465,6 +476,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result> = BTreeMap::new(); let mut all_boxes: BTreeMap> = BTreeMap::new(); for (item, bounds) in items { + if is_seam_fills(&item) { + return Err(bad(cmd, "byColor needs the seam fills' group under every path: move it to the bottom or delete it")); + } if matches!(item.kind, NodeKind::Group { .. }) { return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); } @@ -637,12 +651,12 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { } /// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam -/// fills ([`seams_within`]). +/// fills, if any ([`seams_within`]). pub struct Traced { inputs: TraceInputs, raster: (u32, u32), res: tr::TraceResult, - seams: Vec, + seams: Option, } impl Traced { @@ -669,18 +683,127 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64 tr::TraceError::Cancelled => EngineError::Cancelled, e => EngineError::Other(e.to_string()), })?; - let seams = seams_within(&res, params, MAX_TRACE_ANCHORS); - Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams }) + if !steps(0, 0) { + return Err(EngineError::Cancelled); + } + let size = (raster.width, raster.height); + let outlined = seam_unit(inputs.image.xf, raster_xf(&inputs.image, size)).is_none(); + let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined, steps)?; + Ok(Traced { inputs: inputs.clone(), raster: size, res, seams }) } -/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam -/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the -/// paths, so a trace whose paths have more than half of `max` gets none. -fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec { - if res.anchor_count() > max / 2 { - return vec![]; +/// Pixel space of a `size` raster decoded from `img` → the image object's pixel space → document. +fn raster_xf(img: &ImageObject, size: (u32, u32)) -> vectorcraft_geom::Affine { + let sx = img.width.max(1) as f64 / size.0.max(1) as f64; + let sy = img.height.max(1) as f64 / size.1.max(1) as f64; + img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy) +} + +/// Whether `xf` scales every direction alike (turning and mirroring allowed): its axes keep equal +/// lengths and stay at right angles. +fn scales_alike(xf: vectorcraft_geom::Affine) -> bool { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let (across, down) = (a * a + b * b, c * c + d * d); + let t = across + down; + t.is_finite() && t > 0.0 && (across - down).abs() <= 1e-9 * t && (a * c + b * d).abs() <= 1e-9 * t +} + +/// The smallest length that `xf` scales a unit vector to (its smaller singular value): the +/// difference of the lengths of its turning part and its stretching part. +fn least_scale(xf: vectorcraft_geom::Affine) -> f64 { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let turning = ((a + d) / 2.0).hypot((b - c) / 2.0); + let stretching = ((a - d) / 2.0).hypot((b + c) / 2.0); + (turning - stretching).abs() +} + +/// Document units per raster pixel for the seam fills' strokes when the image object's transform +/// `img_xf` scales every direction alike: the smaller scale of the raster-to-document transform +/// `xf`, so that a stroke 1.5 pixels wide covers at most 0.75 pixels on each side of its edge at +/// any angle. (A raster decoded scaled down to fit can be scaled a little differently across and +/// down, as each side is rounded.) `None` when `img_xf` stretches one direction more than another +/// or is degenerate, where a stroke of any one width would cover more pixels across some edges +/// than across others. +fn seam_unit(img_xf: vectorcraft_geom::Affine, xf: vectorcraft_geom::Affine) -> Option { + let least = least_scale(xf); + (scales_alike(img_xf) && least.is_finite() && least > 0.0).then_some(least) +} + +/// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while +/// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`, +/// each stroke is replaced by a filled path, its outline in raster pixels ([`outline_seams`]), +/// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as +/// many anchors as the paths and the clip at most [`SEAM_CLIP_ANCHORS`], so a trace whose paths +/// have more than half of `max` less four gets none. Outlines, which have more anchors, are +/// counted as each is made, and none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes' +/// anchors would not fit, or once those made so far no longer fit. [`EngineError::Cancelled`] +/// once `steps` answers `false`. +fn seams_within( + res: &tr::TraceResult, + params: &tr::TraceParams, + size: (u32, u32), + max: usize, + outlined: bool, + steps: &(dyn Fn(u64, u64) -> bool + Sync), +) -> Result> { + if res.anchor_count().saturating_mul(2).saturating_add(SEAM_CLIP_ANCHORS) > max { + return Ok(None); + } + let Some(mut seams) = tr::seam_fills(&res.paths, params, size) else { return Ok(None) }; + if outlined { + let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); + let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(SEAM_CLIP_ANCHORS); + if res.anchor_count().saturating_add(estimate) > max { + return Ok(None); + } + let budget = max.saturating_sub(res.anchor_count()).saturating_sub(SEAM_CLIP_ANCHORS); + if !outline_seams(&mut seams.strokes, budget, steps)? { + return Ok(None); + } + seams.strokes.retain(|tp| !tp.path.is_empty()); + if seams.strokes.is_empty() { + return Ok(None); + } + } + Ok(Some(seams)) +} + +/// The most anchors the seam fills' clip has: the image's box cut to the box of the traced paths +/// ([`within_box`]), four corners and at most four more where the image is turned. +const SEAM_CLIP_ANCHORS: usize = 8; + +/// How many seam strokes [`outline_seams`] outlines between asking whether to go on. +const SEAM_OUTLINE_STEP: usize = 64; + +/// Outline each of `strokes` ([`outlined_seam`]) while the outlines' anchors stay within `budget`, +/// asking `steps` every [`SEAM_OUTLINE_STEP`] strokes whether to go on → whether every outline +/// fits (it stops at the first that does not), or [`EngineError::Cancelled`] once `steps` +/// answers `false`. +fn outline_seams(strokes: &mut [tr::TracedPath], budget: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + let mut total = 0usize; + for (i, tp) in strokes.iter_mut().enumerate() { + if i % SEAM_OUTLINE_STEP == 0 && !steps(0, 0) { + return Err(EngineError::Cancelled); + } + outlined_seam(tp); + total = total.saturating_add(tp.path.anchor_count()); + if total > budget { + return Ok(false); + } + } + Ok(true) +} + +/// About how many anchors a seam stroke's outline ([`outlined_seam`]) has for each anchor of the +/// stroke: both sides of each segment and a round join at each anchor. Curves can take more. +const SEAM_OUTLINE_ANCHORS: usize = 6; + +/// Replace a seam stroke `tp` by the area it covers, as a filled path in the same raster pixels: +/// butt caps and round joins, as the strokes have. +fn outlined_seam(tp: &mut tr::TracedPath) { + if let Some(width) = tp.stroke.take() { + tp.path = vectorcraft_pathops::outline_stroke(&tp.path, width, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Round, 4.0); } - tr::seam_fills(&res.paths, params) } /// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] @@ -780,19 +903,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result> = seam_fills + // Abutting: the seam fills, in a clip group of their own under every path, clipped to the + // image's box within the traced paths' box: strokes, or on an image stretched more one + // way, their outlines filled. + let strokes: Vec> = seam_fills .iter() + .flat_map(|f| &f.strokes) .filter_map(|tp| { - let width = tp.stroke?; - let mut n = shape_node(d, tp.path.transformed(xf), None); - n.appearance = Appearance { - items: vec![AppearanceItem::Stroke(StrokeLayer { - cap: LineCap::Butt, - join: LineJoin::Round, - ..StrokeLayer::new(paint_of(tp), width * seam_unit) - })], - ..Default::default() + let outline = match (tp.stroke, seam_unit) { + (Some(width), Some(u)) => { + let mut n = shape_node(d, tp.path.transformed(xf), None); + n.appearance = Appearance { + items: vec![AppearanceItem::Stroke(StrokeLayer { + cap: LineCap::Butt, + join: LineJoin::Round, + ..StrokeLayer::new(paint_of(tp), width * u) + })], + ..Default::default() + } + .into(); + return Some(Arc::new(n)); + } + // The trace leaves strokes only for an image scaled alike in every direction, + // with these same inputs; a stroke is left out here rather than outlined + // outside the anchor limit. + (Some(_), None) => return None, + (None, _) => tp.path.clone(), + }; + if outline.is_empty() { + return None; } - .into(); + let mut n = shape_node(d, outline.transformed(xf), None); + n.appearance = fill_only(paint_of(tp)).into(); Some(Arc::new(n)) }) .collect(); - if !seams.is_empty() { - let mut g = Node::group(d.alloc_id(), seams); - g.name = Some(SEAM_FILLS_NAME.into()); - children.push(Arc::new(g)); - } let mut traced = Vec::with_capacity(res.paths.len()); for tp in res.paths { let paint = paint_of(&tp); @@ -873,6 +1001,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result = f.clip.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| xf * a.p)).collect(); + let inside = within_box(&corners, art); + if inside.len() >= 3 { + let mut clip = shape_node(d, vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&inside, true)), None); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let members = std::iter::once(Arc::new(clip)).chain(strokes).collect(); + let mut g = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + g.name = Some(SEAM_FILLS_NAME.into()); + children.push(Arc::new(g)); + } + } children.extend(grouped(d, traced, &res.parents)); if group_by_color { children = color_groups(c, d, children)?; @@ -894,6 +1039,28 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Vec { + let sides: [&dyn Fn(Point) -> f64; 4] = [&|p| p.x - r.x0, &|p| r.x1 - p.x, &|p| p.y - r.y0, &|p| r.y1 - p.y]; + let mut out = poly.to_vec(); + for side in sides { + let corners = std::mem::take(&mut out); + for (k, &p) in corners.iter().enumerate() { + let Some(&q) = corners.get((k + 1) % corners.len()) else { continue }; + let (dp, dq) = (side(p), side(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp > 0.0 && dq < 0.0) || (dp < 0.0 && dq > 0.0) { + out.push(p + (q - p) * (dp / (dp - dq))); + } + } + } + out +} + /// Images larger than this on a side are traced, but more slowly: the trace says so. pub const LARGE_TRACE_SIDE: u32 = 1500; @@ -1193,7 +1360,7 @@ mod color_group_tests { #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings}; + use super::{MAX_TRACE_ANCHORS, SEAM_CLIP_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings}; use vectorcraft_trace as tr; #[test] @@ -1206,13 +1373,89 @@ mod trace_limit_tests { }); let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() }; let res = tr::trace(&img, ¶ms); - let all = tr::seam_fills(&res.paths, ¶ms); - assert!(!all.is_empty(), "{res:?}"); + let all = tr::seam_fills(&res.paths, ¶ms, (24, 16)); + assert!(all.is_some(), "{res:?}"); let anchors = res.anchor_count(); - // Twice the paths' anchors leaves room for any seam fills. - assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all); + assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + SEAM_CLIP_ANCHORS); + let go = |_: u64, _: u64| true; + // Twice the paths' anchors and the clip's eight at most leave room for any seam fills. + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS, false, &go).unwrap(), all); // One anchor short of that: none. - assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS - 1, false, &go).unwrap(), None); + // Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes' + // anchors each. + let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); + let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); + assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}"); + let n = strokes(all.as_ref().unwrap()); + assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); + // A staircase edge: the outline's round joins give it more anchors than the paths have. The + // outlines are made only when SEAM_OUTLINE_ANCHORS times the strokes' anchors fit. + let img = tr::Raster::from_fn(32, 32, |x, y| if x < y / 4 * 4 + 4 { [200, 40, 50, 255] } else { [30, 90, 200, 255] }); + let params = tr::TraceParams { corners: 100.0, ..params }; + let res = tr::trace(&img, ¶ms); + let anchors = res.anchor_count(); + let all = tr::seam_fills(&res.paths, ¶ms, (32, 32)).unwrap(); + let n = strokes(&all); + let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); + assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined)); + assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); + let fits = anchors + SEAM_OUTLINE_ANCHORS * n + SEAM_CLIP_ANCHORS; + assert!(fits > 2 * anchors + SEAM_CLIP_ANCHORS, "{fits}, {anchors} in the paths"); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true, &go).unwrap(), Some(outlined.clone())); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true, &go).unwrap(), None); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false, &go).unwrap(), Some(all.clone())); + // The outlines are counted as each is made: they stop at the first one past the budget, so + // outlines with more anchors than the estimate allows are refused too. + let need = strokes(&outlined); + assert!(outline_seams(&mut all.strokes.clone(), need, &go).unwrap()); + assert!(!outline_seams(&mut all.strokes.clone(), need - 1, &go).unwrap()); + // Canceled while outlining: the run stops. + let stop = |_: u64, _: u64| false; + assert!(matches!(seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &stop), Err(super::EngineError::Cancelled))); + assert!(matches!(outline_seams(&mut all.strokes.clone(), need, &stop), Err(super::EngineError::Cancelled))); + } + + #[test] + fn within_box_cuts_a_turned_box_to_a_box() { + use vectorcraft_geom::{Point, Rect}; + // A square turned by 45° in a smaller box: each side cuts a corner off, 8 corners. + let diamond = [Point::new(0.0, -10.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0), Point::new(-10.0, 0.0)]; + let cut = super::within_box(&diamond, Rect::new(-6.0, -6.0, 6.0, 6.0)); + assert_eq!(cut.len(), 8, "{cut:?}"); + assert!(cut.iter().all(|p| p.x.abs() <= 6.0 + 1e-12 && p.y.abs() <= 6.0 + 1e-12 && p.x.abs() + p.y.abs() <= 10.0 + 1e-12), "{cut:?}"); + // A corner on a side is kept once. + let square = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0), Point::new(0.0, 4.0)]; + assert_eq!(super::within_box(&square, Rect::new(0.0, 0.0, 4.0, 4.0)), square.to_vec()); + assert_eq!(super::within_box(&square, Rect::new(1.0, 0.0, 4.0, 4.0)).len(), 4); + assert!(super::within_box(&square, Rect::new(5.0, 5.0, 6.0, 6.0)).is_empty()); + } + + #[test] + fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() { + use super::seam_unit; + use vectorcraft_geom::Affine; + assert_eq!(seam_unit(Affine::scale(2.0), Affine::scale(2.0)), Some(2.0)); + assert_eq!(seam_unit(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0]), Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0])), Some(2.0)); + // Turned and scaled alike at any angle, rounding included. + for k in [0.5, 1.0, 3.0, 17.0] { + for i in 0..2000 { + let xf = Affine::rotate(f64::from(i) * std::f64::consts::TAU / 2000.0) * Affine::scale(k); + let unit = seam_unit(xf, xf); + assert!(unit.is_some_and(|u| (u - k).abs() < 1e-9 * k), "{unit:?} at step {i}, scale {k}"); + } + } + let xf = Affine::rotate(0.0496) * Affine::scale(0.5); + assert!(seam_unit(xf, xf).is_some()); + // A raster decoded scaled down to fit (10000 × 7000 pixels as 9791 × 6853) of an image placed + // at 2×: strokes, at the smaller scale. + let (sx, sy) = (10000.0 / 9791.0, 7000.0 / 6853.0); + let unit = seam_unit(Affine::scale(2.0), Affine::scale(2.0) * Affine::scale_non_uniform(sx, sy)).unwrap(); + assert!((unit - 2.0 * f64::min(sx, sy)).abs() < 1e-12, "{unit}"); + assert_eq!(seam_unit(Affine::scale_non_uniform(20.0, 1.0), Affine::scale_non_uniform(20.0, 1.0)), None); + assert_eq!(seam_unit(Affine::skew(0.5, 0.0), Affine::skew(0.5, 0.0)), None); + assert_eq!(seam_unit(Affine::scale_non_uniform(1.0, 0.0), Affine::scale_non_uniform(1.0, 0.0)), None); + assert_eq!(seam_unit(Affine::scale(0.0), Affine::scale(0.0)), None); } #[test] diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 9006b1f4be..a9dee00af3 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Invert Colors", ["Edit", "Edit Colors"], None, - "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}", + "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}", has_selection, |s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert) ), @@ -533,7 +533,7 @@ pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor: let n = recolor(d)?; if let Some(before) = before.filter(|_| n > 0) { super::appearance::capture_series_changes(&before, d, &marks); - super::graph::capture_label_changes(&before, d, &labels, true); + super::graph::capture_label_changes(&before, d, &labels, true, Some(roots)); } Ok(n) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index d863edb96d..a529a3bea9 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -803,8 +803,8 @@ fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Col } } -/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and -/// labels take each time it is drawn again. +/// `f` applied to the series paints, the label styles and the line rows that graph `g` keeps, which +/// its marks, labels and lines take each time it is drawn again. fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { for p in g.series_paints.iter_mut() { for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() { @@ -823,7 +823,10 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color } map_paint_colors(&mut st.stroke, f); } - for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() { + for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows, &mut styles.axis_rows, &mut styles.ring_rows] + .into_iter() + .flatten() + { for paint in [&mut r.paint.fill, &mut r.paint.stroke].into_iter().flatten() { map_paint_colors(paint, f); } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 5571d24b28..c7c5204e5e 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -881,7 +881,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB /// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled with the current fill unless that is None or white (black then), in the document's +/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill, +/// #7975), in the document's /// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result { let mut style = CharStyle::default(); @@ -899,8 +900,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), - None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), - None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)), }; // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none // for the default. Type already in a document keeps its own. diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index b5ac1c13e5..bf03c86746 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -857,14 +857,12 @@ mod tests { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); - s.execute( - "paint.setFill", - &json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), - ) - .unwrap(); + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"gradient": gradient})).unwrap(); let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone(); + // New type starts black (#7975); filled with the gradient, its characters make it a gradient object too. + s.execute("paint.setFill", &json!({"gradient": gradient, "ids": [t]})).unwrap(); let i = s.execute("document.info", &json!({})).unwrap(); - // The type's characters take the current gradient fill, so it is a gradient object too. assert_eq!( (i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()), (Some(1), Some(1), Some(2)) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 38ac35c61a..3c05f35bcc 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), @@ -83,7 +83,7 @@ pub fn specs() -> Vec { "Knife", [], None, - "{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the cut)} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", has_doc, knife ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", has_selection, erase_segments ), @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", has_selection, smooth_region ), @@ -119,7 +119,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", has_doc, join_scrub ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index fd8967f3fa..332ad331dc 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -28,6 +28,27 @@ pub(super) struct Sample { /// x and y. const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"]; +/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation +/// 0..360 degrees (360 is the same direction as 0). +const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)]; + +/// Blob Brush and Eraser Tool Options' Size, in points. +pub(super) const SIZES: (f64, f64) = (0.1, 1000.0); + +/// Blob Brush and Eraser Tool Options' Size Variation, in points. +pub(super) const SIZE_VARIATIONS: (f64, f64) = (0.0, 1000.0); + +/// `v`, or an error naming `key` when it is outside `lo..=hi` (or not a number at all, NaN). +fn within(v: f64, key: &str, (lo, hi): (f64, f64), cmd: &str) -> Result { + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// The number `p` gives for `key`, `default` when it leaves it out or gives null, as [`number_or`] +/// reads it, or an error naming `key` when the number is outside `range`. +pub(super) fn ranged(p: &Value, key: &str, default: f64, range: (f64, f64), cmd: &str) -> Result { + within(number_or(p, key, default, cmd)?, key, range, cmd) +} + /// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite /// number. pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { @@ -42,27 +63,36 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { /// [`points_param`] with what a pen read at each point, as far as it is given: /// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure /// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in -/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is -/// neither a number nor null, is an error. +/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or +/// rotation is neither a number nor null or is outside its range, or an array of more than six +/// numbers, is an error. pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result> { let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; let pts: Vec = a .iter() - .map(|v| { + .enumerate() + .map(|(at, v)| { + const MAX_ITEMS: usize = 2 + PEN_KEYS.len(); + if let Value::Array(xy) = v + && xy.len() > MAX_ITEMS + { + let key = format!("{key}[{at}]"); + return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries"))); + } let mut pen = [None; 4]; - for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() { + for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() { let given = match v { Value::Array(xy) => xy.get(i + 2), _ => v.get(*key), }; *slot = match given { None | Some(Value::Null) => None, - Some(n @ Value::Number(_)) => n.as_f64(), + Some(n @ Value::Number(_)) => n.as_f64().map(|x| within(x, key, range, cmd)).transpose()?, Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), }; } let [pressure, tx, ty, rotation] = pen; - let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0))); + let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0))); Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation }) }) .collect::>()?; @@ -186,18 +216,14 @@ impl PenRecord { } /// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with -/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for -/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size. +/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None` +/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the +/// size. A `sizeVariation` outside its range is an error with Fixed too. pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result> { + let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?; match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { None | Some(Ok("fixed")) => Ok(None), - Some(Ok("pressure")) => { - let variation = number_or(p, "sizeVariation", 0.0, cmd)?; - if !(variation.is_finite() && variation >= 0.0) { - return Err(bad(cmd, "sizeVariation must be 0 or more")); - } - Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))) - } + Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))), Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), } diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index fca15e46c5..ae150c7bb4 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,6 +1,6 @@ use super::common::{ - PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, - samples_param, sibling_with, size_pressure, target_paths, usize_opt, + PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, + pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, @@ -293,10 +293,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { return erase_rect(s, marquee_param(rect, C)?); } let samples = samples_param(p, "points", C)?; - let size = number_or(p, "size", 10.0, C)?; - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } + let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; let vary = eraser_variations(p, C)?; @@ -401,12 +398,13 @@ const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bea /// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with /// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation` -/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how -/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null -/// is 0; any other mode, or a variation that is negative or past its most, is refused. +/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points, at most 1000), its +/// mode and how far it varies either way. A mode left out or null is Fixed, and a variation left +/// out or null is 0; any other mode, or a variation that is negative or past its most, is refused, +/// in every mode. fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> { const KEYS: [(&str, &str, f64); 3] = - [("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)]; + [("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", SIZE_VARIATIONS.1)]; let mut out = [(Variation::Fixed, 0.0); 3]; for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) { let mode = match p.get(mode_key).filter(|v| !v.is_null()) { @@ -419,7 +417,11 @@ fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> { return Err(bad(cmd, format!("{var_key} must be 0 or more"))); } if variation > most { - return Err(bad(cmd, format!("{var_key} must be at most {most}"))); + // Size Variation is refused as path.blob refuses it. + return Err(match var_key { + "sizeVariation" => bad(cmd, format!("`{var_key}` must be from {} to {most}", SIZE_VARIATIONS.0)), + _ => bad(cmd, format!("{var_key} must be at most {most}")), + }); } *slot = (mode, variation); } diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 55f5fe267b..9ca565667d 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,6 +1,6 @@ use super::common::{ - PenRecord, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, - subpath_len, target_paths, within_input_bound, + PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure, + stroke_paint, subpath_len, target_paths, within_input_bound, }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, @@ -486,10 +486,7 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec pub(super) fn blob(s: &mut Session, p: &Value) -> Result { const C: &str = "path.blob"; let samples = samples_param(p, "points", C)?; - let size = number_or(p, "size", 10.0, C)?; - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } + let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; if !angle.is_finite() || !roundness.is_finite() { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 1f471d84a3..c5e5969247 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool { /// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at /// the document's raster effects resolution or a Rasterize effect's finer one, with whether they -/// all paint below it (shadows and outer glows: the image then holds just them). A group's or -/// layer's image leaves out its members' raster effects, which are expanded with them. `None` -/// when it has none. -fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { +/// all paint below it (shadows and outer glows: the image then holds just them, and paints with +/// their blend mode when they all use one). A group's or layer's image leaves out its members' +/// raster effects, which are expanded with them. `None` when it has none. +/// `Err` when that image would take `budget` past its limits: the object then stays as it is. +fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result, OverBudget> { let fx = rasterfx::raster_fx(n); if fx.is_empty() { - return None; + return Ok(None); } let below = fx.iter().all(effects::RasterFx::is_below); - Some((rasterfx::raster_image(d, n, below, true)?, below)) + let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?; + let mut image = rasterfx::raster_image(d, n, below, true); + if image.is_none() { + // No image was made: it takes nothing from the budget. + budget.images += 1; + budget.pixels += pixels; + } + // Rendered alone, over nothing, the shadows and glows can't blend with the art below the + // object, so the image does, as the canvas draws them. + let mut modes = fx.iter().filter_map(effects::RasterFx::mode); + if below + && let (Some(mode), Some(image)) = (modes.next(), image.as_mut()) + && modes.all(|m| m == mode) + { + image.blend = mode; + } + Ok(image.map(|image| (image, below))) +} + +/// The most images of raster effects one Expand Appearance makes. +const MAX_RASTER_IMAGES: u32 = 1_024; + +/// The most pixels the images of raster effects one Expand Appearance makes hold in all. +const MAX_RASTER_PIXELS: u64 = 256_000_000; + +/// The note when objects keep their raster effects because their images would take an Expand +/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`]. +pub(crate) const RASTER_EFFECTS_LEFT: &str = + "some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all"; + +/// An image of raster effects that would take a [`RasterBudget`] past its limits. +#[derive(Debug)] +struct OverBudget; + +/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the +/// objects whose raster effects it left as they are because their images would go past them. +pub(crate) struct RasterBudget { + images: u32, + pixels: u64, + pub(crate) left: usize, +} + +impl RasterBudget { + pub(crate) fn new() -> Self { + Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 } + } + + /// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return + /// them; `Err`, with its object counted in `left`, when it would go past what is left. + fn take(&mut self, pixels: u64) -> std::result::Result { + if self.images == 0 || pixels > self.pixels { + self.left += 1; + return Err(OverBudget); + } + self.images -= 1; + self.pixels -= pixels; + Ok(pixels) + } } /// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that @@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { /// pieces with the ids they have before that. `kept` gets the new id of each object in them that /// had an id `skip` lists before. Returns what each of those other members' expansions lists, by /// the member's new id. +#[allow(clippy::too_many_arguments)] fn expand_pieces( d: &mut Document, m: &mut Node, @@ -991,6 +1050,7 @@ fn expand_pieces( skip: &[NodeId], kept: &mut Vec, stroke_art: effects::StrokeArt, + raster: &mut RasterBudget, ) -> std::collections::HashMap> { let id = m.id; let mut seen = std::collections::HashSet::from([id]); @@ -1005,7 +1065,7 @@ fn expand_pieces( if all || c.id == id { effects::expand_art(d, c, stroke_art); } else if has_seeded(c) && repeats_an_id(c, &seen) { - listed = Some(expand_in_place(d, c, brushes, skip)); + listed = Some(expand_in_place(d, c, brushes, skip, raster)); } let mut was = vec![]; if !skip.is_empty() { @@ -1030,37 +1090,65 @@ fn expand_pieces( } /// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose -/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as -/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so -/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more -/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art -/// would take the objects placed so far past `budget`. -fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) { +/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`], +/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in +/// that art in turn, so [`expand_pieces`] bakes their effects with the rest. +fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) { for c in m.children_mut().into_iter().flatten() { if !matches!(c.kind, NodeKind::SymbolInstance { .. }) { if c.children().is_some() { - expand_nested_instances(d, Arc::make_mut(c), depth, budget); + expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster); } continue; } - let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue }; - if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) { - continue; - } - let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue }; - let count = sym.art.count() as u64; - if count > *budget { - continue; - } - *budget -= count; - let art = vectorcraft_render::instance_art(&sym.art, c); - if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) { - expand_nested_instances(d, &mut a, depth + 1, budget); + if let Some(a) = expanded_instance(d, c, depth, budget, raster) { *c = Arc::new(a); } } } +/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster +/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art +/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as +/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when +/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance +/// staying as it is, when its active fill and stroke have no such effect, it is more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would +/// take the objects placed so far past `budget`, or the image of its raster effects would take +/// `raster` past its limits. When that image can't be made, they stay on the art its geometry +/// effects make, and without one it stays as it is. +fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None }; + let has_raster = effects::has_instance_row_raster(c); + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) { + return None; + } + let sym = d.symbols.iter().find(|s| s.name == *symbol)?; + let count = sym.art.count() as u64; + if count > *budget { + return None; + } + let art = vectorcraft_render::instance_art(&sym.art, c); + let image = if has_raster { raster_image(d, c, raster).ok()? } else { None }; + *budget -= count; + let mut v = c.clone(); + if image.is_some() { + rasterfx::strip_raster(&mut v, false); + } + let below = match image { + Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)), + Some((image, true)) => Some(image), + None => None, + }; + let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art)) + .or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?; + expand_nested_instances(d, &mut a, depth + 1, budget, raster); + if let Some(image) = below { + rasterfx::put_below(d, &mut a, image); + } + Some(a) +} + /// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids? fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { let mut ids = std::collections::HashSet::new(); @@ -1075,9 +1163,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet) -> bool { type Listed = (NodeId, usize); /// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`. -fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec { +fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec { let mut listed = vec![]; - if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) { + if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) { *c = e; } listed @@ -1099,18 +1187,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections: /// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and /// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art), /// geometry effects are baked, raster effects become an embedded image, and the object keeps its -/// transparency. -pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) { - expand_node_except(d, id, brushes, &[], out); +/// transparency. An object whose raster effects' image would take `raster` past its limits stays +/// as it is, with what is inside it. +pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec, raster: &mut RasterBudget) { + expand_node_except(d, id, brushes, &[], out, raster); } /// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry /// effect of a group or layer around one still reshapes it with the rest of its members, and the /// copies of it that such an effect makes are left as they are too. -fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) { +fn expand_node_except( + d: &mut Document, + id: NodeId, + brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + out: &mut Vec, + raster: &mut RasterBudget, +) { let Some(n) = d.node(id).cloned() else { return }; let mut listed = vec![]; - let m = expanded_node(d, n, brushes, skip, &mut listed); + let m = expanded_node(d, n, brushes, skip, &mut listed, raster); out.extend(listed.into_iter().map(|(id, _)| id)); if let Some(mut m) = m { // Art made from type takes its emoji's pixels into the document. @@ -1124,11 +1220,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush /// [`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. -fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec) -> Option { +fn expanded_node( + d: &mut Document, + mut n: Node, + brushes: &[vectorcraft_brush::Brush], + skip: &[NodeId], + out: &mut Vec, + raster: &mut RasterBudget, +) -> Option { let id = n.id; if skip.contains(&id) || !expandable(&n) { return None; } + // What `out` held before `n`: an object left by the raster budget lists nothing. + let listed_before = out.len(); // Colour adjustments: the colours inside become the adjusted ones (an embedded image a // recoloured copy), then the rest of the appearance expands. let mut changed = false; @@ -1141,6 +1246,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } _ => 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()) + .then(|| d.images.keys().cloned().collect::>()); if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1163,7 +1272,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br for (i, c) in m.children_mut().into_iter().flatten().enumerate() { let c = Arc::make_mut(c); if i == 0 { - expanded = expand_in_place(d, c, brushes, skip); + expanded = expand_in_place(d, c, brushes, skip, raster); fresh_ids_listed(d, c, &mut seen, &mut expanded); } else { effects::fresh_ids(d, c, &mut seen); @@ -1186,7 +1295,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } return Some(m); } - let image = raster_image(d, &n); + // 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 { + out.truncate(listed_before); + if let Some(keys) = images_before { + d.images.retain(|k, _| keys.contains(k)); + } + return None; + }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = @@ -1206,7 +1323,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } 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); + members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) @@ -1224,10 +1341,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br } _ => None, }; - effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { + // A symbol instance whose active fill or stroke has only effects that paint below it + // (now in the image) becomes its art as well. + let row_raster = image.is_some() && effects::has_instance_row_raster(&n); + let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref()) + .or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None }); + outlined.map(|mut m| { let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES; - expand_nested_instances(d, &mut m, 1, &mut budget); - expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art); + expand_nested_instances(d, &mut m, 1, &mut budget, raster); + expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster); m }) }; @@ -1262,7 +1384,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br match members.remove(&c.id) { Some(listed) => out.extend(listed), None => { - if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) { *c = Arc::new(e); changed = true; } @@ -1336,6 +1458,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { } let failed = vectorcraft_render::decode_failures(); let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); + let mut raster = RasterBudget::new(); let ids = s.edit("Expand Appearance", |d, _| { let before = d.clone(); // The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose @@ -1351,7 +1474,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let mut out = vec![]; let threaded = super::threads::frames(d); for id in &roots { - expand_node_except(d, *id, &brushes, &designs, &mut out); + expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster); } super::dimension::put_back(d, lifted); // A dimension whose source was replaced stays where it was, no longer linked. @@ -1360,6 +1483,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { // stays type under a new id takes its frame's place. super::threads::leave_threads(d, &threaded); if out.is_empty() || (kept && d.layers == before.layers) { + if raster.left > 0 { + return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into())); + } return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into())); } super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?; @@ -1367,8 +1493,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { })?; let mut out = json!({ "ids": ids_json(&ids) }); // Raster effects become images rendered from the art. - if let Some(w) = rasterfx::undecoded_warning(failed) { - out["warning"] = json!(w); + let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect(); + if !warnings.is_empty() { + out["warning"] = json!(warnings.join("; ")); + } + if raster.left > 0 { + out["rasterLeft"] = json!(raster.left); } Ok(out) } diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index b3389e190d..f7e7206c57 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1082,3 +1082,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() { let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count(); assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art"); } + +/// The raster budget charges each image its pixels before it is made: an image past what is left +/// is refused and counted, and the object keeps its blur. +#[test] +fn an_image_past_the_pixels_left_stays_unmade() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap(); + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let n = d.node(id).cloned().unwrap(); + let pixels = super::rasterfx::raster_pixels(&d, &n, false, true); + assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}"); + + let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 }; + assert!(super::raster_image(&mut d, &n, &mut budget).is_err()); + assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken"); + + let mut budget = super::RasterBudget { images: 10, pixels, left: 0 }; + let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made"); + let NodeKind::Image(img) = &image.kind else { panic!("not an image") }; + assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size"); + assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0)); + + 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"); +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 657cab3060..e814975417 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index c5b8858f98..c2140477ad 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -268,6 +268,8 @@ struct RasterOptions { /// PSD: Write Layers. layers: Option, max_editability: Option, + /// PSD: Preserve Text Editability (with layers). + preserve_text: Option, hidden_layers: Option, /// Appearance of Black › Printing / Exporting (`prefs.blackOutput`); agents can set it here too. rich_black: Option, @@ -350,6 +352,7 @@ impl RasterOptions { color_model, layers: self.layers.unwrap_or(true), max_editability: self.max_editability.unwrap_or(false), + preserve_text: self.preserve_text.unwrap_or(false), hidden_layers: self.hidden_layers.unwrap_or(false), embed_icc, }, @@ -374,6 +377,7 @@ fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> { let r = match format { RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()), RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()), + RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()), RasterFormat::Bmp => o.bmp.check(), RasterFormat::Tga => o.tga.check(), _ => Ok(()), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 75b202c8ab..2429d5763f 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -318,6 +318,13 @@ const MAX_EDITABILITY: FormatOption = FormatOption { description: "with layers: layers and sublayers become groups and every object a layer of its own, named as the Layers panel names it (text by its text); clipping, masked or knockout layers stay one layer", }; +const PRESERVE_TEXT: FormatOption = FormatOption { + name: "preserveText", + ty: "boolean", + default: "false", + description: "with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers (with their pixels); a layer holding such type becomes a group of its type layers and pixel layers of the art between them, unless other art in it blends in a mode other than normal; refused with layers: false", +}; + const PSD_HIDDEN_LAYERS: FormatOption = FormatOption { name: "hiddenLayers", ty: "boolean", @@ -339,6 +346,7 @@ const PSD_OPTIONS: &[FormatOption] = &[ ANTI_ALIAS, COLOR_MODEL, PSD_LAYERS, + PRESERVE_TEXT, MAX_EDITABILITY, PSD_HIDDEN_LAYERS, EMBED_ICC, diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index 23168f1e25..028d9fe5a6 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result let one = super::save::artboard_doc(doc, b); let (full, placed) = crate::cmd::place::document::full_documents(&one); let mut d = full.into_owned(); - expand_appearances(&mut d); + if expand_appearances(&mut d) { + note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT); + } if mode == SeeThrough::Flatten { expand_image_patterns(&mut d)?; } @@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result Ok(enc) } -/// Expand Appearance of every layer's art whose appearance the format can't hold. -fn expand_appearances(d: &mut Document) { +/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether +/// objects kept raster effects whose images would go past Expand Appearance's limits. +fn expand_appearances(d: &mut Document) -> bool { let brushes = vectorcraft_brush::library(d); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); let mut out = vec![]; + let mut raster = super::super::effectcmd::RasterBudget::new(); for id in layers { - super::super::effectcmd::expand_node(d, id, &brushes, &mut out); + super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster); } + raster.left > 0 } /// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint, diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 61e5fede2a..c4ab3d4ab0 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -764,7 +764,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) { /// Export settings kept in the document or a preset, as the request being served may see them: a /// `folder` outside the read roots ([`super::access::shown`]) is left out. -fn leave_out_unreadable_settings_folder(mut settings: Map) -> Map { +pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map) -> Map { if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) { settings.remove("folder"); } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 44928bf176..bcc01e37a4 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> }) } +/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` +/// outside the read roots of the request being served (the open document keeps it). +fn native_attachment(doc: &Document) -> Vec { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return vectorcraft_format::save(doc, false); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + vectorcraft_format::save(&kept, false) +} + /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they /// link to and the writer's warnings. pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result { let (opts, boards, chosen) = plan(doc, p)?; // Preserve editing embeds the native document (once, shared by every file). - let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false)); + let native = opts.preserve_editing.then(|| native_attachment(doc)); // Draw linked files as vectors when available, or their previews with a warning. Keep // that preparation out of the native attachment so missing links remain relinkable. let (full, warnings) = crate::cmd::place::document::full_documents(doc); diff --git a/crates/engine/src/cmd/fileio/tests_psd.rs b/crates/engine/src/cmd/fileio/tests_psd.rs index d4f03d78a3..42f87af488 100644 --- a/crates/engine/src/cmd/fileio/tests_psd.rs +++ b/crates/engine/src/cmd/fileio/tests_psd.rs @@ -69,6 +69,23 @@ fn psd_writes_layers_groups_and_text_named_after_it() { assert!(s.execute("document.export", &json!({"format": "psd", "colorModel": "lab"})).is_err()); } +#[test] +fn preserve_text_writes_point_type_as_type_layers_and_needs_layers() { + let mut s = session(); + let file = export(&mut s, json!({"preserveText": true})); + let (_, count, names) = layers(&file); + assert_eq!((count, names), (-4, vec!["Layer 1".into(), "".into(), "Hello".into(), "Words".into()]), "Words becomes a group"); + assert_eq!(file.windows(8).filter(|w| w == b"8BIMTySh").count(), 1, "one type layer"); + assert_eq!(export(&mut s, json!({"preserveText": false})), export(&mut s, json!({}))); + // Without layers there are no type layers to write. + let err = s.execute("document.export", &json!({"format": "psd", "layers": false, "preserveText": true})).unwrap_err().to_string(); + assert!(err.contains("preserveText") && err.contains("layers: true"), "{err}"); + assert!(s.execute("document.export", &json!({"format": "psd", "preserveText": "yes"})).is_err()); + // Other formats don't take it. + let r = s.execute("document.export", &json!({"format": "png", "preserveText": true})).unwrap(); + assert!(r["warnings"].to_string().contains("preserveText"), "{r}"); +} + #[test] fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() { let mut s = Session::new(); @@ -79,7 +96,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() { (psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()), (Some("PSD"), Some(true), Some(true), Some(true)) ); - for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] { + for k in ["colorModel", "layers", "preserveText", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] { assert!(psd["options"].get(k).is_some(), "psd takes {k}"); } let r = s.execute("document.export", &json!({"format": "psd", "useArtboards": true})).unwrap(); diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 541cdd1118..5a000c3327 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,15 @@ pub fn specs() -> Vec { always, font_list ), + cmd!( + query "text.similarFonts", + "Show Similar Fonts", + [], + None, + "{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000", + always, + similar_fonts + ), cmd!( query "text.glyphCategories", "Glyph Categories", @@ -1146,6 +1155,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result { } } +/// The most families `text.similarFonts` takes as its `limit`. +const MAX_SIMILAR: u64 = 100_000; + +fn similar_fonts(_: &mut Session, p: &Value) -> Result { + const C: &str = "text.similarFonts"; + let db = vectorcraft_text::FontDb::global(); + let family = match p.get("family") { + Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(), + Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")), + Some(_) => return Err(bad(C, "`family` must be a string")), + }; + let limit = match p.get("limit") { + None => None, + Some(v) => Some( + v.as_u64() + .filter(|n| (1..=MAX_SIMILAR).contains(n)) + .ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?, + ), + }; + // Any of the family's names, spelled as the font menus list it; a family they don't list is not available. + let menu = db.menu_family_list(); + let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned()); + let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) }; + let mut families = db.similar_families(&family, &menu); + if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) { + families.truncate(n); + } + Ok(json!({ "family": family, "families": families })) +} + /// `text.glyphCategories`: the OpenType categories of a font's glyphs /// ([`vectorcraft_text::FontFace::glyph_categories`]). fn glyph_categories(_: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index ad0164a62c..71a5e36ccf 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", has_doc, add_point ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 00575695d4..af0f4cfcda 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label", has_doc, edit_gradient ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label", has_doc, set_gradient_geom ), diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 11a41174c1..301d361a1a 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -48,9 +48,11 @@ use generate::generate; #[cfg(test)] use series::default_series_color; pub(crate) use series::{ - LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, - is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, + LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, + capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, + capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows, + capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art, + is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index 59455ca4f3..7341636a90 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -543,7 +543,7 @@ impl<'a> Plot<'a> { } for v in tick_values(lo, hi, step).into_iter().skip(1) { let ring: Vec = (0..ncat).map(|c| at(c, v)).collect(); - axes.push(self.b.path(polyline(&ring, true), Paint::None, Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25)); + axes.push(self.b.ring(polyline(&ring, true))); } let ax = self.b.group("Axes", axes); self.b.out.push(ax); diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 8e56ad8ae6..8d0ea64e45 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -82,9 +82,49 @@ fn kept_rows(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vecto } } -/// Give label `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their kept order and -/// place relative to the characters, and the object opacity and blend mode. An opacity read from a file is held to 0..1 -/// and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt). +/// What a graph line is, for the rows it keeps: an axis line or tick mark, or a ring of a radar graph. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Line { + Axis, + Ring, +} + +impl Line { + /// The stroke and weight the graph draws lines of this kind with when they keep no rows. They have no fill. + fn default_stroke(self) -> (Paint, f64) { + match self { + Line::Axis => (Paint::solid(Color::BLACK), 0.5), + Line::Ring => (Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25), + } + } + + /// The rows ([`super::series::label_rows`]) a line of this kind shows as the graph draws it with no kept rows. + pub(super) fn default_rows(self) -> vectorcraft_doc::LabelRows { + let (stroke, width) = self.default_stroke(); + let paint = vectorcraft_doc::SeriesPaint { fill: Some(Paint::None), stroke: Some(stroke), stroke_width: Some(width), ..Default::default() }; + vectorcraft_doc::LabelRows { paint, ..Default::default() } + } +} + +/// The rows lines of kind `line` keep, if any. +pub(super) fn kept_line_rows(styles: &vectorcraft_doc::LabelStyles, line: Line) -> Option<&vectorcraft_doc::LabelRows> { + match line { + Line::Axis => styles.axis_rows.as_ref(), + Line::Ring => styles.ring_rows.as_ref(), + } +} + +/// The slot of `styles` that holds the rows lines of kind `line` keep. +pub(super) fn line_slot(styles: &mut vectorcraft_doc::LabelStyles, line: Line) -> &mut Option { + match line { + Line::Axis => &mut styles.axis_rows, + Line::Ring => &mut styles.ring_rows, + } +} + +/// Give label or graph line `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their +/// kept order and place relative to the contents, and the object opacity and blend mode. An opacity read from a file is +/// held to 0..1 and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt). fn apply_label_rows(n: &mut Node, kept: &vectorcraft_doc::LabelRows) { use vectorcraft_doc::{AppearanceItem, FillLayer, StrokeLayer}; let rows = &kept.paint; @@ -124,7 +164,20 @@ impl Gen<'_> { let mut bp = BezPath::new(); bp.move_to(a); bp.line_to(b); - self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5) + self.kept_line(Line::Axis, PathData::from_bezpath(&bp)) + } + /// A ring of a radar graph through `pd`. + pub(super) fn ring(&mut self, pd: PathData) -> Arc { + self.kept_line(Line::Ring, pd) + } + /// A graph line of kind `line` through `pd`, with the rows lines of its kind keep, else its default stroke. + fn kept_line(&mut self, line: Line, pd: PathData) -> Arc { + let (stroke, width) = line.default_stroke(); + let mut n = Node::path(self.d.alloc_id(), pd, Appearance::basic(Paint::None, stroke, width)); + if let Some(rows) = kept_line_rows(self.styles, line) { + apply_label_rows(&mut n, rows); + } + Arc::new(n) } pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc { let t = self.text_object(role, at, s, justify); diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index c3cf55ca60..3f787513f4 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -4,7 +4,7 @@ use vectorcraft_geom::Shape; use super::axis::radar_axis; use super::generate::is_dark; -use super::labels::{Role, filled_lines_on, label_para, label_size, label_style}; +use super::labels::{Line, Role, filled_lines_on, kept_line_rows, label_para, label_size, label_style, line_slot}; use super::{ Affine, Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad, refresh_bounds, @@ -155,13 +155,32 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec { } /// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series -/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other -/// ids and the art of a graph design pass through, and the order of `ids` is kept. +/// group: the graph draws its series groups again with no rows of their own. A graph's Axes group is replaced by the +/// lines and labels directly inside it, and its Legend group by the labels directly inside it, which the graph keeps +/// rows for ([`capture_label_rows`]). A group with no such member, other ids and the art of a graph design pass +/// through, and the order of `ids` is kept. pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec { series_group_marks_where(doc, ids, |_| true) } -/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through. +/// The lines and labels directly in `n` when it is the Axes group of a graph, or the labels directly in it when it is +/// the graph's Legend group, in paint order. `None` for any other object. +pub(crate) fn graph_part_members(doc: &Document, n: &Node) -> Option> { + if !matches!(n.kind, NodeKind::Group { .. }) || n.extras().series_index.is_some() { + return None; + } + let axes = match n.name.as_deref() { + Some("Axes") => true, + Some("Legend") => false, + _ => return None, + }; + let spec = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref())?; + let member = |c: &Node| matches!(c.kind, NodeKind::Text(_)) || (axes && line_in(spec, n, c).is_some()); + Some(n.children().into_iter().flatten().filter(|c| member(c)).map(|c| c.id).collect()) +} + +/// [`series_group_marks`] for the series groups, Axes groups and Legend groups `stands` accepts; the others pass +/// through. pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec { let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); @@ -172,6 +191,10 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); if marks.is_empty() { out.push(*id) } else { out.extend(marks) } } + Some(part) if stands(part) => match graph_part_members(doc, part) { + Some(members) if !members.is_empty() => out.extend(members), + _ => out.push(*id), + }, _ => out.push(*id), } } @@ -1185,21 +1208,34 @@ pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], metho /// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels /// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or /// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so -/// they undo together. Returns whether a kept style changed. +/// they undo together. A kind that keeps no style and that `change` leaves at the default style keeps none, unless +/// `change` sets the legend fill. Returns whether a kept style changed. pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { let mut changed = false; for (graph, role) in label_kinds(doc, ids) { - changed |= store_label_style(doc, graph, role, change); + changed |= store_label_style(doc, graph, role, change, true); + } + changed +} + +/// [`capture_label_styles`], except that a kind that keeps no style keeps the default style when `change` leaves it +/// unchanged, for a command that gives character attributes (a size equal to the labels' own, for example). +pub(crate) fn capture_label_styles_given(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { + let mut changed = false; + for (graph, role) in label_kinds(doc, ids) { + changed |= store_label_style(doc, graph, role, change, false); } changed } /// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that /// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether -/// the kept style or that mark changed. -fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool { +/// the kept style or that mark changed. With `unless_default`, a kind that keeps no style and that `change` leaves at +/// the default style keeps none, unless `change` sets the legend fill. +fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle), unless_default: bool) -> bool { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false }; - let mut style = label_style(&spec.label_styles, role); + let was = label_style(&spec.label_styles, role); + let mut style = was.clone(); // The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one // of two different fills something else. let sets_fill = role == Role::Legend @@ -1215,6 +1251,9 @@ fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Role::Category => &mut styles.categories, Role::Legend => &mut styles.legend, }; + if unless_default && slot.is_none() && style == was && !(sets_fill && !styles.legend_fill_set) { + return false; + } let mut changed = slot.as_ref() != Some(&style); *slot = Some(style); if sets_fill && !styles.legend_fill_set { @@ -1277,37 +1316,356 @@ pub(crate) fn label_rows(n: &Node) -> Option { (rows != vectorcraft_doc::LabelRows::default()).then_some(rows) } +/// The graph and kind of graph line `id`: a path directly in a graph's Axes group. Looked up through its parents, with no +/// pass over the document. +fn graph_line(doc: &Document, id: NodeId) -> Option<(NodeId, Line)> { + let line = doc.node(id)?; + if !matches!(line.kind, NodeKind::Path { .. }) { + return None; + } + let path = doc.ancestry(id)?; + let [.., graph, axes, _] = path.as_slice() else { return None }; + let spec = doc.node(*graph)?.extras().graph.as_deref()?; + Some((*graph, line_in(spec, doc.node(*axes)?, line)?)) +} + +/// The kind of graph line `line` is when `axes` is the Axes group of a graph drawn from `spec` and `line` a path directly +/// in it. A radar graph's rings are its closed paths; its spokes, open, are axis lines. +fn line_in(spec: &GraphSpec, axes: &Node, line: &Node) -> Option { + if axes.name.as_deref() != Some("Axes") || axes.extras().series_index.is_some() || !matches!(axes.kind, NodeKind::Group { .. }) { + return None; + } + let NodeKind::Path { path, .. } = &line.kind else { return None }; + Some(if spec.kind == GraphKind::Radar && path.is_closed() { Line::Ring } else { Line::Axis }) +} + +/// The graph lines among `ids`, each with its graph and kind, from the back to the front and each once: a later line's +/// capture replaces an earlier one's, so the frontmost line of a kind sets what the kind keeps. +fn lines_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, NodeId, Line)> { + let mut out: Vec<(NodeId, NodeId, Line)> = ids.iter().filter_map(|id| graph_line(doc, *id).map(|(g, line)| (*id, g, line))).collect(); + out.sort_by_cached_key(|(id, ..)| doc.index_path(*id)); + out.dedup_by_key(|(id, ..)| *id); + out +} + +/// Which of the object rows ([`label_rows`]) a graph label or line shows its kind keeps after an edit. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Keep { + /// All of them. + All, + /// Only the object opacity and blend mode; the fill and stroke rows stay as the kind keeps them. + Object, + /// The fill and stroke rows; the object opacity and blend mode stay as the kind keeps them. + Rows, + /// The fill row with `fill`, the stroke row with `stroke`, and the object opacity and blend mode with `object`; the + /// others stay as the kind keeps them. Each row keeps its place relative to the characters; a row taken from the + /// label or line paints above a kept row on the same side of them, unless the label or line shows it below its own row + /// of that kind. + Kinds { fill: bool, stroke: bool, object: bool }, +} + +/// The kinds (true: fill) of the rows in `rows` from the bottom up, each with whether it paints below the characters. +fn row_places(rows: &vectorcraft_doc::LabelRows) -> Vec<(bool, bool)> { + let order = if rows.stroke_under { [false, true] } else { [true, false] }; + let has = |fill: bool| if fill { rows.paint.fill.is_some() } else { rows.paint.stroke.is_some() }; + let below = usize::from(rows.below.unwrap_or(0)); + order.into_iter().filter(|k| has(*k)).enumerate().map(|(i, k)| (k, i < below)).collect() +} + +/// Where the rows paint when the row of kind `taken` (true: fill) comes from `shown` and the row of the other kind from +/// `kept`, each keeping its place relative to the characters: `below` and `stroke_under` of [`vectorcraft_doc::LabelRows`]. +fn merged_places(kept: &vectorcraft_doc::LabelRows, shown: &vectorcraft_doc::LabelRows, taken: bool) -> (Option, bool) { + let in_shown = row_places(shown); + let t = in_shown.iter().copied().find(|p| p.0 == taken); + let o = row_places(kept).into_iter().find(|p| p.0 != taken); + let order = match (t, o) { + (Some(t), Some(o)) => { + // Rows on different sides of the characters: the one below them is lower. On the same side: as the label or + // line shows them, else the taken row on top. + let at = |kind: bool| in_shown.iter().position(|p| p.0 == kind); + let o_first = if t.1 != o.1 { + o.1 + } else { + match (at(!taken), at(taken)) { + (Some(o_at), Some(t_at)) => o_at < t_at, + _ => true, + } + }; + if o_first { vec![o, t] } else { vec![t, o] } + } + (t, o) => t.into_iter().chain(o).collect(), + }; + let below = order.iter().filter(|p| p.1).fold(0u8, |k, _| k + 1); + ((below > 0).then_some(below), order.len() == 2 && !order[0].0) +} + +/// `shown` with the parts of the rows `kept` keeps that `keep` leaves as they are. +fn keep_rows(kept: vectorcraft_doc::LabelRows, shown: vectorcraft_doc::LabelRows, keep: Keep) -> vectorcraft_doc::LabelRows { + match keep { + Keep::All => shown, + Keep::Object => { + let mut kept = kept; + (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + kept + } + Keep::Rows => { + let mut shown = shown; + (shown.paint.opacity, shown.paint.blend) = (kept.paint.opacity, kept.paint.blend); + shown + } + Keep::Kinds { fill, stroke, object } => { + let places = match (fill, stroke) { + (true, true) => (shown.below, shown.stroke_under), + (false, false) => (kept.below, kept.stroke_under), + (taken, _) => merged_places(&kept, &shown, taken), + }; + let mut rows = shown; + (rows.below, rows.stroke_under) = places; + let (r, k) = (&mut rows.paint, kept.paint); + if !object { + (r.opacity, r.blend) = (k.opacity, k.blend); + } + if !fill { + (r.fill, r.fill_opacity, r.fill_blend, r.fill_unit_box) = (k.fill, k.fill_opacity, k.fill_blend, k.fill_unit_box); + } + if !stroke { + (r.stroke, r.stroke_width, r.stroke_opacity, r.stroke_blend, r.stroke_unit_box) = + (k.stroke, k.stroke_width, k.stroke_opacity, k.stroke_blend, k.stroke_unit_box); + } + rows + } + } +} + +/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), of which `keep` says what is +/// taken from the line: `None` when that is how the graph draws them with no kept rows. +fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, keep: Keep) -> Option { + let shown = label_rows(n).unwrap_or_default(); + let rows = keep_rows(slot.cloned().unwrap_or_else(|| line.default_rows()), shown, keep); + (rows != line.default_rows()).then_some(rows) +} + +/// Keep the object rows ([`label_rows`]) of the graph lines among `ids` for every line of their kind (axis lines and tick +/// marks, or a radar graph's rings), the part of them `keep` says, even when a line already showed them. Returns whether +/// kept rows changed. +fn store_line_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { + let mut changed = false; + for (id, graph, line) in lines_of(doc, ids) { + let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { continue }; + let Some(n) = doc.node(id) else { continue }; + let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, keep); + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Keep the object rows of graph lines `ids` for every line of their kind, as [`capture_label_rows`] keeps a label's, +/// for an edit that wrote their fill or stroke. Lines of a kind that the edit reached differently take the frontmost +/// one's rows. Called inside the same edit, so they undo together. Returns whether kept rows changed. +pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_line_rows(doc, ids, Keep::All) +} + +/// [`capture_line_rows`] for an edit that wrote the fill and stroke rows of graph lines `ids` and left their object +/// opacity and blend mode alone: those stay as the kind keeps them, also when a line still shows other ones until the +/// graph is drawn again. +pub(crate) fn capture_line_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_line_rows(doc, ids, Keep::Rows) +} + +/// Keep, for every line of their kind, the attributes of the object rows ([`label_rows`]) that an edit changed on the +/// graph lines among `ids` (`before`: the document before the edit). The attributes the edit left alone stay as the kind +/// keeps them, also when a line still shows other ones until the graph is drawn again. Lines of a kind that the edit +/// changed differently take the frontmost one's attributes. Called inside the same edit, so they undo together. Returns +/// whether kept rows changed. +pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool { + let mut changed = false; + for (id, graph, line) in lines_of(doc, ids) { + let old = before.node(id).and_then(label_rows).unwrap_or_default(); + let new = doc.node(id).and_then(label_rows).unwrap_or_default(); + if old == new { + continue; + } + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); + merge_row_edits(&mut rows, &old, &new); + let kept = (rows != line.default_rows()).then_some(rows); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Keep, for every line of their kind, the paint an edit wrote to row `at` of graph line `id` for each `(id, at)` in +/// `written` when that row is the line's topmost visible fill or stroke, also when the line already showed that paint: +/// the paint replaces the one its kind keeps from another line. The other attributes stay as the kind keeps them. Lines +/// of a kind take the frontmost one's paint. Called inside the same edit, so they undo together. Returns whether kept +/// rows changed. +pub(crate) fn capture_line_paint_writes(doc: &mut Document, written: &[(NodeId, usize)]) -> bool { + let paint = RowWrites { paint: true, ..RowWrites::NONE }; + capture_line_row_writes(doc, written, paint, paint) +} + +/// Which attributes of a fill or stroke row an edit wrote, for [`capture_line_row_writes`]. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct RowWrites { + /// The paint. + pub paint: bool, + /// The weight (a stroke row only). + pub weight: bool, + /// The row's opacity. + pub opacity: bool, + /// The row's blend mode. + pub blend: bool, +} + +impl RowWrites { + /// No attribute. + pub const NONE: RowWrites = RowWrites { paint: false, weight: false, opacity: false, blend: false }; +} + +/// [`capture_line_paint_writes`] for the attributes `fill` says of a written fill row and `stroke` says of a written +/// stroke row: each is kept for every line of the kind as the line shows it, also when the line already showed it, in +/// place of what its kind keeps from another line. +pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, usize)], fill: RowWrites, stroke: RowWrites) -> bool { + let ids: Vec = written.iter().map(|(id, _)| *id).collect(); + let mut changed = false; + for (id, graph, line) in lines_of(doc, &ids) { + let Some(n) = doc.node(id) else { continue }; + let items = &n.appearance.items; + let wrote = |kind: bool| items.iter().rposition(|it| it.is_fill() == kind && it.visible()).is_some_and(|at| written.contains(&(id, at))); + let on_fill = if wrote(true) { fill } else { RowWrites::NONE }; + let on_stroke = if wrote(false) { stroke } else { RowWrites::NONE }; + if on_fill == RowWrites::NONE && on_stroke == RowWrites::NONE { + continue; + } + let shown = label_rows(n).unwrap_or_default().paint; + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); + let k = &mut rows.paint; + if on_fill.paint { + k.fill = shown.fill; + } + if on_fill.opacity { + k.fill_opacity = shown.fill_opacity; + } + if on_fill.blend { + k.fill_blend = shown.fill_blend; + } + if on_stroke.paint { + k.stroke = shown.stroke; + } + if on_stroke.weight { + k.stroke_width = shown.stroke_width; + } + if on_stroke.opacity { + k.stroke_opacity = shown.stroke_opacity; + } + if on_stroke.blend { + k.stroke_blend = shown.stroke_blend; + } + let kept = (rows != line.default_rows()).then_some(rows); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Is `id` a graph line: a path directly in a graph's Axes group? +pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool { + graph_line(doc, id).is_some() +} + +/// Set each attribute of `rows` that differs between `old` and `new` as `new` has it. +fn merge_row_edits(rows: &mut vectorcraft_doc::LabelRows, old: &vectorcraft_doc::LabelRows, new: &vectorcraft_doc::LabelRows) { + fn take(kept: &mut T, old: &T, new: &T) { + if old != new { + *kept = new.clone(); + } + } + let (k, o, n) = (&mut rows.paint, &old.paint, &new.paint); + take(&mut k.fill, &o.fill, &n.fill); + take(&mut k.stroke, &o.stroke, &n.stroke); + take(&mut k.stroke_width, &o.stroke_width, &n.stroke_width); + take(&mut k.fill_opacity, &o.fill_opacity, &n.fill_opacity); + take(&mut k.stroke_opacity, &o.stroke_opacity, &n.stroke_opacity); + take(&mut k.fill_blend, &o.fill_blend, &n.fill_blend); + take(&mut k.stroke_blend, &o.stroke_blend, &n.stroke_blend); + take(&mut k.opacity, &o.opacity, &n.opacity); + take(&mut k.blend, &o.blend, &n.blend); + take(&mut rows.below, &old.below, &new.below); + take(&mut rows.stroke_under, &old.stroke_under, &new.stroke_under); +} + +/// Would [`store_line_rows`] with [`Keep::Object`] change what a graph keeps for the lines among `ids`? Reads the +/// document without copying it. +fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { + let mut kept: Vec<(NodeId, Line, Option)> = vec![]; + for (id, graph, line) in lines_of(doc, ids) { + let (Some(spec), Some(n)) = (doc.node(graph).and_then(|n| n.extras().graph.as_deref()), doc.node(id)) else { continue }; + let slot = match kept.iter().position(|(g, l, _)| *g == graph && *l == line) { + Some(i) => kept.swap_remove(i).2, + None => kept_line_rows(&spec.label_styles, line).cloned(), + }; + kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, Keep::Object))); + } + kept.into_iter().any(|(graph, line, rows)| { + doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|spec| kept_line_rows(&spec.label_styles, line) != rows.as_ref()) + }) +} + /// Keep the object rows ([`label_rows`]) of graph labels `ids` for every label of their kind, as /// [`capture_label_styles`] keeps a character format, even when a label already showed them: the last label of a kind /// in the order of `ids` sets what that kind keeps. Objects other than type are left out before the graph's labels are -/// looked up. Called inside the same edit, so they undo together. Returns whether kept rows changed. +/// looked up. The graph lines among `ids` keep their rows for every line of their kind too ([`capture_line_rows`]). +/// Called inside the same edit, so they undo together. Returns whether kept rows changed. pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, false) + store_label_rows(doc, ids, Keep::All) } -/// Keep the object opacity and blend mode of graph labels `ids` for every label of their kind, as [`capture_label_rows`] -/// keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph keeps changed. +/// Keep the object opacity and blend mode of graph labels and graph lines `ids` for every label or line of their kind, as +/// [`capture_label_rows`] keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph +/// keeps changed. pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, true) + store_label_rows(doc, ids, Keep::Object) +} + +/// Keep, for every label or line of their kind, the fill row (with `fill`) and the stroke row (with `stroke`) that graph +/// labels and graph lines `ids` show, and with `object` their object opacity and blend mode, as [`capture_label_rows`] +/// keeps them, for an edit that wrote only those: a row of the other kind stays as the kind keeps it, also when a label or +/// line still shows its own one until the graph is drawn again. Returns whether what the graph keeps changed. +pub(crate) fn capture_label_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool { + store_label_rows(doc, ids, Keep::Kinds { fill, stroke, object }) +} + +/// [`capture_label_kind_rows`] for the graph lines among `ids` alone. +pub(crate) fn capture_line_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool { + store_line_rows(doc, ids, Keep::Kinds { fill, stroke, object }) } /// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying /// it. pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { - label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| { - let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false }; - let slot = match role { - Role::Value => &spec.label_styles.values_rows, - Role::Category => &spec.label_styles.categories_rows, - Role::Legend => &spec.label_styles.legend_rows, - }; - *slot != kept_label_rows(slot, rows, true) - }) + line_object_opacity_differs(doc, ids) + || label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| { + let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false }; + let slot = match role { + Role::Value => &spec.label_styles.values_rows, + Role::Category => &spec.label_styles.categories_rows, + Role::Legend => &spec.label_styles.legend_rows, + }; + *slot != kept_label_rows(slot, rows, Keep::Object) + }) } -/// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`]. -fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool { - let mut changed = false; +/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_kind_rows`], as `keep` says. +fn store_label_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { + let mut changed = store_line_rows(doc, ids, keep); for (graph, role, rows) in label_rows_of(doc, ids) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let slot = match role { @@ -1315,26 +1673,23 @@ fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bo Role::Category => &mut spec.label_styles.categories_rows, Role::Legend => &mut spec.label_styles.legend_rows, }; - let kept = kept_label_rows(slot, rows, object_only); + let kept = kept_label_rows(slot, rows, keep); changed |= *slot != kept; *slot = kept; } changed } -/// What a kind keeps after a label of it shows `rows`: those rows, or with `object_only` what `slot` keeps with the -/// label's object opacity and blend mode. +/// What a kind keeps (`slot`) after a label of it shows `rows`, of which `keep` says what is taken from the label. fn kept_label_rows( slot: &Option, rows: Option, - object_only: bool, + keep: Keep, ) -> Option { - if !object_only { + if keep == Keep::All { return rows; } - let mut kept = slot.clone().unwrap_or_default(); - let shown = rows.unwrap_or_default(); - (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + let kept = keep_rows(slot.clone().unwrap_or_default(), rows.unwrap_or_default(), keep); (kept != vectorcraft_doc::LabelRows::default()).then_some(kept) } @@ -1454,23 +1809,38 @@ pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool { g.picks_legend_fill() } -/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them. +/// The graph labels and graph lines among `roots` and inside them, for an edit that reaches them without naming them. pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec { let mut texts = Vec::new(); + let mut lines = Vec::new(); for id in roots { + // A root that is a line, or the Axes group: found through its parents. + if graph_line(doc, *id).is_some() { + lines.push(*id); + } let Some(root) = doc.node(*id) else { continue }; + if let Some(parent) = doc.parent_of(*id).and_then(|p| doc.node(p)) + && let Some(spec) = parent.extras().graph.as_deref() + { + lines.extend(root.children().into_iter().flatten().filter(|c| line_in(spec, root, c).is_some()).map(|c| c.id)); + } root.walk(&mut |n| { if matches!(n.kind, NodeKind::Text(_)) { texts.push(n.id); } + if let Some(spec) = n.extras().graph.as_deref() { + for axes in n.children().into_iter().flatten() { + lines.extend(axes.children().into_iter().flatten().filter(|c| line_in(spec, axes, c).is_some()).map(|c| c.id)); + } + } }); } // Graph labels are type: without type among `roots`, the graph's labels are not looked up. - if texts.is_empty() { - return texts; + if !texts.is_empty() { + let labels = graph_labels(doc); + texts.retain(|id| labels.contains_key(id)); } - let labels = graph_labels(doc); - texts.retain(|id| labels.contains_key(id)); + texts.extend(lines.into_iter().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))); // Nested roots (a graph and one of its labels) reach a label twice. texts.sort_unstable(); texts.dedup(); @@ -1482,10 +1852,14 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec { /// and stroke attributes ([`RUN_PAINT`]) that changed on all of a label's characters, on the kind's kept style. The /// frontmost label of a kind sets what that kind keeps, whatever order `ids` are in. On a graph that colors its legend /// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one -/// fill. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. -pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool) -> bool { +/// fill and the edit named them: with `named`, only a legend label among `named` (an edit that reached the others +/// through the graph or a group leaves them the graph's black or white); without it, every label in `ids`. The graph +/// lines among `ids` whose rows changed keep what changed for every line of their kind ([`capture_line_changes`]), with or without +/// `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. +pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool, named: Option<&[NodeId]>) -> bool { + let lines = capture_line_changes(before, doc, ids); if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) { - return false; + return lines; } let labels = graph_labels(doc); let mut picked: Vec = ids.iter().copied().filter(|id| labels.contains_key(id)).collect(); @@ -1510,18 +1884,25 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: if rows && label_rows(was) != label_rows(now) { changed_rows.push(id); } - let fill = kind.1 != Role::Legend || one_fill(kind.0); + let aimed = !wedge_fills.contains_key(&kind.0) || named.is_none_or(|n| n.contains(&id)); + let fill = kind.1 != Role::Legend || (one_fill(kind.0) && aimed); characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change))); } - let mut changed = capture_label_rows(doc, &changed_rows); + let mut changed = capture_label_rows(doc, &changed_rows) | lines; for ((graph, role), (style, entries)) in &characters { - changed |= store_label_style(doc, *graph, *role, &|st| { - for i in entries { - if let Some(copy) = RUN_PAINT.get(*i) { - copy(style, st); + changed |= store_label_style( + doc, + *graph, + *role, + &|st| { + for i in entries { + if let Some(copy) = RUN_PAINT.get(*i) { + copy(style, st); + } } - } - }); + }, + true, + ); } changed } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 3b18820f4b..c1a59c30e5 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -7762,6 +7762,936 @@ fn a_recolor_leaves_wedge_legend_labels_their_contrast() { assert_eq!(kept.and_then(|f| f.color()).map(|c| c.to_hex()).as_deref(), Some("#ffffff")); } +/// A recolor of the whole graph that turns every wedge legend label the same color (one series) still leaves them to +/// the graph's black or white, so a label stays readable when its wedge is painted light again. +#[test] +fn a_recolor_of_a_one_series_pie_leaves_its_wedge_label_its_contrast() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a\nP1,1"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap(); + // The white wedge turns black and its black label white. + s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(spec(&s, id).label_styles.legend, None); + s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1]]})).unwrap(); + let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") }; + assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#000000")); +} + +/// The lines in graph `id`'s Axes group (axis lines, tick marks and a radar graph's rings), in paint order. +fn line_nodes(s: &Session, id: NodeId) -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Axes").children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Text(_))).map(|c| (**c).clone()).collect() +} + +/// How line `n` looks: its stroke color (empty without one), stroke weight and object opacity. +fn line_look(n: &vectorcraft_doc::Node) -> (String, f64, f32) { + let stroke = n.appearance.stroke_paint().color().map(|c| c.to_hex()).unwrap_or_default(); + (stroke, n.appearance.stroke_width(), n.opacity) +} + +/// The looks of graph `id`'s lines after it is drawn again. +fn redrawn_line_looks(s: &mut Session, id: NodeId) -> Vec<(String, f64, f32)> { + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + line_nodes(s, id).iter().map(line_look).collect() +} + +/// A stroke, a weight, no stroke or an opacity given to one axis line is kept for every axis line and tick mark when the +/// graph is drawn again, and undo takes it back with its edit. +#[test] +fn paint_set_on_one_axis_line_is_kept_for_every_line() { + let cases = [ + ("paint.setStroke", json!({"color": "#ff0000"}), ("#ff0000", 0.5, 1.0)), + ("stroke.set", json!({"weight": 2}), ("#000000", 2.0, 1.0)), + ("paint.setStroke", json!({"none": true}), ("", 0.0, 1.0)), + ("appearance.clear", json!({}), ("", 0.0, 1.0)), + ("transparency.set", json!({"opacity": 40}), ("#000000", 0.5, 0.4)), + ]; + every_case(cases, |(cmd, params, (hex, width, opacity))| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + assert!(lines.len() > 2, "{lines:?}"); + let mut p = params.clone(); + p["ids"] = json!([lines[0].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + let want = (hex.to_string(), *width, *opacity); + assert!(looks.iter().all(|l| (&l.0, (l.1 - want.1).abs() < 1e-9, (l.2 - want.2).abs() < 1e-6) == (&want.0, true, true)), "{cmd}: {looks:?}"); + // Undo takes back the redraw, then the edit and what the graph keeps. + for _ in 0..2 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(spec(&s, id).label_styles.axis_rows, None, "{cmd}"); + }); +} + +/// A recolor of the whole graph, or Swap Fill and Stroke on its axis lines, is kept for its axis lines, and the labels' +/// paint stays its own. +#[test] +fn recoloring_a_graph_keeps_its_axis_lines_paint() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ffffff"), "inverted black lines are white"); + let ids: Vec = line_nodes(&s, id).iter().map(|n| n.id.0).collect(); + s.execute("paint.swap", &json!({"ids": ids})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap(); + assert_eq!((kept.paint.fill.and_then(|p| p.color()).map(|c| c.to_hex()), kept.paint.stroke), (Some("#ffffff".into()), Some(Paint::None))); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the lines have no stroke after the swap"); + // The value labels keep their inverted fill, not the lines' swapped paint. + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label_paint: Vec<(String, bool)> = group(&n, "Axes") + .children() + .unwrap() + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Text(t) => Some((t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default(), t.runs[0].style.stroke.is_none())), + _ => None, + }) + .collect(); + assert!(!label_paint.is_empty() && label_paint.iter().all(|l| *l == ("#ffffff".to_string(), true)), "{label_paint:?}"); +} + +/// A stroke given the whole graph, or its Axes group, is kept for its axis lines. +#[test] +fn a_stroke_given_the_whole_graph_or_its_axes_group_is_kept_for_its_axis_lines() { + for axes in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let target = if axes { group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id } else { id }; + s.execute("paint.setStroke", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000"), "axes: {axes}"); + } +} + +/// A radar graph's rings keep what is set on one of them, apart from its spokes. +#[test] +fn a_radar_graphs_rings_keep_their_paint_apart_from_its_spokes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let lines = line_nodes(&s, id); + // Three categories: three spokes, then the rings. + assert_eq!(line_look(&lines[3]), ("#999999".into(), 0.25, 1.0)); + s.execute("paint.setStroke", &json!({"ids": [lines[3].id.0], "color": "#00ff00"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#000000" && l.1 == 0.5), "{looks:?}"); + assert!(looks[3..].iter().all(|l| l.0 == "#00ff00" && l.1 == 0.25), "{looks:?}"); + s.execute("paint.setStroke", &json!({"ids": [line_nodes(&s, id)[0].id.0], "color": "#0000ff"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#00ff00"), "{looks:?}"); +} + +/// When an edit gives axis lines different paint, the frontmost one sets what they keep, whatever order `ids` are in. +#[test] +fn the_frontmost_axis_line_sets_what_its_recolor_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (back, front) = (lines[0].id, lines[lines.len() - 1].id); + s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap(); + s.execute("edit.colors.invert", &json!({"ids": [front.0, back.0]})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#00ffff"), "the inverted red of the frontmost line"); +} + +/// An appearance moved from an axis line to one behind it is kept for every axis line, not the cleared source's. +#[test] +fn an_appearance_moved_to_an_axis_line_behind_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (back, front) = (lines[0].id, lines[lines.len() - 1].id); + s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap(); + s.execute("appearance.transfer", &json!({"source": front.0, "target": back.0})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#ff0000"), "the moved red, not the cleared source"); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000")); +} + +/// A radar graph's spoke brought in front of its rings is still a spoke: what is set on it is kept for the spokes. +#[test] +fn a_radar_spoke_moved_in_front_of_the_rings_keeps_its_kind() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let spoke = line_nodes(&s, id)[0].id; + s.execute("object.arrange.bringToFront", &json!({"ids": [spoke.0]})).unwrap(); + assert_eq!(line_nodes(&s, id).last().map(|n| n.id), Some(spoke), "the spoke is in front of the rings"); + s.execute("paint.setStroke", &json!({"ids": [spoke.0], "color": "#0000ff"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#999999"), "{looks:?}"); +} + +/// A graphic style linked to an axis line passes a redefinition on to every axis line. +#[test] +fn a_redefined_graphic_style_on_an_axis_line_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Axis"})).unwrap(); + let line = line_nodes(&s, id)[0].id; + s.execute("graphicStyle.apply", &json!({"name": "Axis", "ids": [line.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Axis", "id": rect.0})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#00ff00")); +} + +/// An Eyedropper pick and Apply Stroke to Fill on an axis line are kept for every axis line. +#[test] +fn an_eyedropper_pick_and_stroke_to_fill_on_an_axis_line_are_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + let line = line_nodes(&s, id)[0].id; + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000" && l.1 == 1.0), "the picked 1 pt red stroke"); + let line = line_nodes(&s, id)[1].id; + s.execute("addon.color.strokeToFill", &json!({"ids": [line.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let fills: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == "#ff0000"), "{fills:?}"); +} + +/// Setting a line to the paint it is drawn with by default keeps nothing, and is no edit. +#[test] +fn axis_lines_given_their_default_paint_keep_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#000000"})).unwrap(); + assert_eq!(spec(&s, id).label_styles.axis_rows, None); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); +} + +/// `object.setProps` and `transparency.set` without an `item` keep only a line's object opacity: the stroke its kind +/// keeps from another line stays, though the line they are given still shows the default stroke. +#[test] +fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + for (cmd, params) in [("object.setProps", json!({"opacity": 50})), ("transparency.set", json!({"opacity": 50}))] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{cmd}: {looks:?}"); + } +} + +/// A reorder that leaves an axis line's rows as they were keeps what its kind keeps from another line and is no edit. +#[test] +fn a_reorder_that_changes_nothing_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let stroke = top_row(&s, lines[1].id, false); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "from": stroke, "to": stroke})).unwrap(); + s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "indices": [stroke], "to": stroke})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); +} + +/// An Eyedropper pick that applies only the object's transparency to an axis line keeps the stroke its kind keeps, though +/// the line it is applied to still shows the default stroke. +#[test] +fn a_transparency_only_pick_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.set", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + let apply = json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}"); +} + +/// The Eyedropper Options that apply every fill and stroke attribute but not the object's transparency. +fn every_row_attribute_without_transparency() -> serde_json::Value { + let fill = json!({"color": true, "transparency": true, "overprint": true}); + let stroke = + json!({"color": true, "transparency": true, "overprint": true, "weight": true, "cap": true, "join": true, "miter": true, "dash": true}); + json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}) +} + +/// An Eyedropper pick of every fill and stroke attribute without the object's transparency, with or without `append`, +/// keeps the object opacity the axis lines keep from another line, though the line it is applied to still shows 100%. +#[test] +fn a_pick_without_transparency_on_an_axis_line_keeps_the_opacity_its_kind_keeps() { + for append in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("transparency.set", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).2, 1.0, "append {append}: the other lines show 100% until the graph is drawn again"); + let pick = json!({"source": rect.0, "ids": [lines[1].id.0], "apply": every_row_attribute_without_transparency(), "append": append}); + s.execute("appearance.copyFrom", &pick).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "append {append}: {looks:?}"); + } +} + +/// A graphic style added on top of a graph label's or axis line's appearance keeps the object opacity its kind keeps +/// from another label or line, though the one it is added to still shows 100%. +#[test] +fn a_graphic_style_added_to_a_label_or_axis_line_keeps_the_opacity_its_kind_keeps() { + for label in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Red"})).unwrap(); + let (first, second) = if label { + (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")) + } else { + let lines = line_nodes(&s, id); + (lines[0].id, lines[1].id) + }; + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node(second).unwrap().opacity, 1.0, "label {label}: 100% until the graph is drawn again"); + s.execute("graphicStyle.apply", &json!({"name": "Red", "ids": [second.0], "add": true})).unwrap(); + if label { + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, opacity) = rows_of(&looks, q); + assert!((opacity - 0.4).abs() < 1e-6 && rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?} {opacity}"); + } + } else { + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "{looks:?}"); + } + } +} + +/// A fill-only graphic style added on top of a graph label or axis line, or a fill-only source appended to one with the +/// Eyedropper, keeps the stroke its kind keeps from another label or line, though the one it is added to still shows its +/// own. +#[test] +fn a_fill_added_to_a_label_or_axis_line_keeps_the_stroke_its_kind_keeps() { + let cases = [(false, false), (false, true), (true, false), (true, true)]; + every_case(cases, |&(label, append)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (first, second) = if label { + (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")) + } else { + let lines = line_nodes(&s, id); + (lines[0].id, lines[1].id) + }; + if label { + s.execute("appearance.addStroke", &json!({"ids": [first.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [first.0], "index": top_row(&s, first, false), "color": "#ff0000"})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [first.0], "color": "#ff0000"})).unwrap(); + } + if append { + let pick = json!({"source": rect.0, "ids": [second.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + } else { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [second.0], "add": true})).unwrap(); + } + if label { + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, _) = rows_of(&looks, q); + let shows = |fill: bool, hex: &str| rows.iter().any(|r| r.0 == fill && r.1 == hex); + assert!(shows(false, "#ff0000") && shows(true, "#0000ff"), "{q}: {rows:?}"); + } + } else { + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); + } + }); +} + +/// A stroke a label's kind keeps below the characters stays below them when a fill-only graphic style is added on top of +/// another label of the kind, or a fill-only source appended to it, and the new fill paints above the characters. +#[test] +fn a_fill_added_to_a_label_keeps_the_kept_stroke_below_the_characters() { + every_case([false, true], |&append| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")); + s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap(); + s.execute("appearance.moveItem", &json!({"ids": [q1.0], "from": "contents", "to": 1})).unwrap(); + if append { + let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + } else { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [q2.0], "add": true})).unwrap(); + } + redrawn_label_rows(&mut s, id); + let look = |ap: &vectorcraft_doc::Appearance| (ap.contents_at(), ap.items.iter().map(|it| it.is_fill()).collect::>()); + for q in ["Q1", "Q2", "Q3"] { + assert_eq!(look(&label_node(&s, id, "Axes", q).appearance), (1, vec![false, true]), "append {append}: {q}"); + } + }); +} + +/// A Contents (Characters) row move that leaves a graph label as it was keeps the rows its kind keeps from another label +/// and is no edit. +#[test] +fn a_contents_move_that_changes_nothing_on_a_label_keeps_the_rows_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")); + s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [q1.0], "index": top_row(&s, q1, false), "color": "#ff0000"})).unwrap(); + let at = s.doc().unwrap().doc.node(q2).unwrap().appearance.contents_at(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("appearance.moveItem", &json!({"ids": [q2.0], "from": "contents", "to": at})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, _) = rows_of(&looks, q); + assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}"); + } +} + +/// An Eyedropper pick with `append` and without the object's transparency on a graph label keeps the object opacity its +/// kind keeps from another label, though the label it is applied to still shows 100%. +#[test] +fn an_appended_pick_without_transparency_on_a_label_keeps_the_opacity_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + s.execute("transparency.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0], "opacity": 40})).unwrap(); + let q2 = text_id(&s, id, "Axes", "Q2"); + assert_eq!(s.doc().unwrap().doc.node(q2).unwrap().opacity, 1.0, "Q2 shows 100% until the graph is drawn again"); + let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, opacity) = rows_of(&looks, q); + assert!((opacity - 0.4).abs() < 1e-6, "{q}: {opacity}"); + assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}"); + } +} + +/// An edit of some attributes on an axis line that still shows the default stroke keeps what it changes, and the stroke +/// its kind keeps from another line stays: a cap is not kept, so it changes nothing the kind keeps. +#[test] +fn an_edit_of_some_attributes_on_an_axis_line_keeps_the_rest_its_kind_keeps() { + let cases = [ + ("stroke.set", json!({"cap": "round"}), ""), + ("paint.setFill", json!({"color": "#0000ff"}), "#0000ff"), + ("appearance.setItem", json!({"index": 0, "color": "#00ff00"}), "#00ff00"), + ]; + for (cmd, params, fill) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#ff0000".into(), 0.5, 1.0)), "{cmd}: {looks:?}"); + let fills: Vec = + line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == fill), "{cmd}: {fills:?}"); + } +} + +/// An opacity and a stroke weight given to a radar graph's ring are kept for its rings, and its spokes keep their own. +#[test] +fn transparency_and_stroke_weight_on_a_radar_ring_are_kept_for_its_rings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let ring = line_nodes(&s, id)[3].id; + s.execute("transparency.set", &json!({"ids": [ring.0], "opacity": 40})).unwrap(); + s.execute("stroke.set", &json!({"ids": [ring.0], "weight": 1})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{looks:?}"); + assert!(looks[3..].iter().all(|l| l.0 == "#999999" && l.1 == 1.0 && (l.2 - 0.4).abs() < 1e-6), "{looks:?}"); +} + +/// A placed gradient on an axis line's stroke is kept for every axis line without its placement. +#[test] +fn a_gradient_on_an_axis_line_is_kept_without_its_placement() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + s.execute("paint.editGradient", &json!({"ids": [line.0], "kind": "linear", "stroke": true})).unwrap(); + let placement = json!({"ids": [line.0], "stroke": true, "start": [100, 100], "end": [200, 100], "aspect": 50}); + s.execute("paint.setGradientGeom", &placement).unwrap(); + let shown = line_nodes(&s, id)[0].appearance.stroke_paint().clone(); + assert!(matches!(&shown, Paint::Gradient(g) if g.geom.is_some()), "the line's gradient is placed: {shown:?}"); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke; + assert!(matches!(&kept, Some(Paint::Gradient(g)) if g.geom.is_none() && g.freeform.is_none()), "{kept:?}"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(line_nodes(&s, id).iter().all(|n| matches!(n.appearance.stroke_paint(), Paint::Gradient(_)))); +} + +/// Default Fill and Stroke and Apply Fill to Stroke on an axis line are kept for every axis line. +#[test] +fn default_fill_and_stroke_and_fill_to_stroke_on_an_axis_line_are_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.default", &json!({"ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke"); + let fills: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == "#ffffff"), "{fills:?}"); + let line = line_nodes(&s, id)[1].id; + s.execute("paint.setFill", &json!({"ids": [line.0], "color": "#0000ff"})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#0000ff"), "the blue fill on the stroke"); +} + +/// The Appearance commands and `graphicStyle.apply` given a graph's Axes group or Legend group edit the lines and labels +/// directly in it, as given a series group they edit its paths: every line and label of each kind keeps what they set +/// when the graph is drawn again, and the groups keep no rows of their own. +#[test] +fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let part = |s: &Session, name: &str| group(s.doc().unwrap().doc.node(id).unwrap(), name).clone(); + s.execute("appearance.clear", &json!({"ids": [part(&s, "Axes").id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the cleared lines have no stroke"); + let (_, blue) = blue_style(&mut s, "Blue", false); + for name in ["Axes", "Legend"] { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [part(&s, name).id.0]})).unwrap(); + } + let kept = spec(&s, id).label_styles; + let fill = |rows: Option| rows.and_then(|r| r.paint.fill); + assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "axis lines"); + assert_eq!(fill(kept.values_rows), Some(blue.clone()), "value labels"); + assert_eq!(fill(kept.legend_rows), Some(blue.clone()), "legend labels"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + for name in ["Axes", "Legend"] { + let g = part(&s, name); + assert!(g.appearance.items.is_empty(), "{name} keeps no rows of its own"); + let members: Vec = g.children().unwrap().iter().map(|c| c.appearance.fill_paint()).collect(); + assert!(!members.is_empty() && members.iter().all(|p| *p == blue), "{name}: {members:?}"); + } +} + +/// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row +/// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph +/// keeps the change when it is drawn again. +#[test] +fn a_row_index_given_the_axes_group_is_a_row_of_its_backmost_member_with_aligned() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let back = axes.children().unwrap()[0].id; + assert!(line_nodes(&s, id).iter().any(|l| l.id == back), "the backmost member is a line"); + let stroke = top_row(&s, back, false); + for (cmd, p) in [ + ("appearance.setItem", json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000"})), + ("appearance.removeItem", json!({"ids": [axes.id.0], "index": stroke})), + ("appearance.duplicateItem", json!({"ids": [axes.id.0], "index": stroke})), + ("appearance.moveItem", json!({"ids": [axes.id.0], "from": stroke, "to": 0})), + ("transparency.set", json!({"ids": [axes.id.0], "item": stroke, "opacity": 40})), + ] { + let err = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(err.contains("aligned"), "{cmd}: {err}"); + } + let labels = |s: &Session| -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Axes").children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| (*c.appearance).clone()).collect() + }; + let was = labels(&s); + s.execute("appearance.setItem", &json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000", "aligned": true})).unwrap(); + s.execute("transparency.set", &json!({"ids": [axes.id.0], "item": stroke, "opacity": 40, "aligned": true})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); + let rows = spec(&s, id).label_styles.axis_rows.unwrap(); + assert_eq!(rows.paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + let now = labels(&s); + assert!(!now.is_empty() && now.iter().all(|a| *a == was[0]), "the labels keep their rows"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let l = &group(&n, "Axes").children().unwrap()[0]; + assert!((l.appearance.items[top_row(&s, l.id, false)].opacity() - 0.4).abs() < 1e-6, "the stroke row's opacity is kept"); +} + +/// An aligned row edit given the Axes group leaves alone what a kind of label keeps from a label without that row: the +/// category labels keep the orange fill row of one of them through an edit of the lines' stroke rows. +#[test] +fn an_aligned_row_edit_given_the_axes_group_keeps_the_rows_of_labels_it_did_not_reach() { + let cases = [("appearance.setItem", json!({"color": "#0000ff"})), ("appearance.duplicateItem", json!({})), ("appearance.removeItem", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let c = text_id(&s, id, "Axes", "Q2"); + s.execute("appearance.addFill", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [c.0], "index": 0, "color": "#ff8000"})).unwrap(); + let kept = spec(&s, id).label_styles.categories_rows; + assert!(kept.is_some(), "the category labels keep the orange row"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let back = axes.children().unwrap()[0].id; + let mut p = params.clone(); + p["ids"] = json!([axes.id.0]); + p["index"] = json!(top_row(&s, back, false)); + p["aligned"] = json!(true); + s.execute(cmd, &p).unwrap(); + assert_eq!(spec(&s, id).label_styles.categories_rows, kept, "{cmd}"); + }); +} + +/// An edit of a hidden row of an axis line leaves what its kind keeps from another line: the line's visible rows did not +/// change. +#[test] +fn an_edit_of_a_hidden_row_of_an_axis_line_keeps_what_its_kind_keeps() { + let cases = [ + ("appearance.setItem", json!({"color": "#0000ff"})), + ("appearance.duplicateItem", json!({})), + ("appearance.removeItem", json!({})), + ("transparency.set", json!({"opacity": 40})), + ("paint.setStroke", json!({"color": "#0000ff"})), + ]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let line = lines[1].id; + s.execute("appearance.addStroke", &json!({"ids": [line.0]})).unwrap(); + let hidden = top_row(&s, line, false); + s.execute("appearance.setItem", &json!({"ids": [line.0], "index": hidden, "visible": false})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows; + let mut p = params.clone(); + p["ids"] = json!([line.0]); + p[if cmd.starts_with("appearance.") { "index" } else { "item" }] = json!(hidden); + s.execute(cmd, &p).unwrap(); + assert_eq!(spec(&s, id).label_styles.axis_rows, kept, "{cmd}"); + }); +} + +/// An Eyedropper pick of only the object's opacity, or of only stroke options the graph does not keep, on an axis line +/// keeps the stroke its kind keeps from another line, though the line it is given still shows the default stroke. +#[test] +fn an_eyedropper_pick_of_only_the_opacity_keeps_the_stroke_its_kind_keeps() { + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let stroke = |dash: bool| json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": dash}); + let cases = [ + (json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke(false)}}), 0.5), + (json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke(true)}}), 1.0), + ]; + every_case(cases, |(pick, opacity)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + s.execute("stroke.set", &json!({"ids": [rect.0], "dash": [4, 2]})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "pickUp": pick})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - *opacity).abs() < 1e-6), "{pick}: {looks:?}"); + }); +} + +/// Default Fill and Stroke on a label or an axis line that already shows the default paint is kept for its kind, in +/// place of the paint the kind keeps from another label or line. +#[test] +fn default_fill_and_stroke_on_a_label_or_line_that_shows_it_is_kept_for_its_kind() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("paint.setFill", &json!({"ids": [text_id(&s, id, "Axes", "4").0], "color": "#ff0000"})).unwrap(); + let hex = |st: &CharStyle| st.fill.color().map(|c| c.to_hex()); + assert_eq!(hex(&label_run_style(&s, id, "Axes", "0")).as_deref(), Some("#000000"), "the other labels show black until the graph is drawn again"); + s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "0").0]})).unwrap(); + label_looks(&mut s, id); + let st = label_run_style(&s, id, "Axes", "4"); + assert_eq!((hex(&st).as_deref(), st.stroke.is_none()), (Some("#000000"), true)); + let lines = line_nodes(&s, id); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke"); +} + +/// Default Fill and Stroke on a label of a kind that keeps no style, which already shows the default paint, is no edit. +#[test] +fn default_fill_and_stroke_on_a_label_that_shows_it_is_no_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "4").0]})).unwrap(); + assert_eq!(spec(&s, id).label_styles.values, None); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); +} + +/// Redefine Graphic Style on an Axes group linked to the style with rows of its own (as a file can hold it) restyles and +/// links the lines and labels in it, and clears and unlinks the group; Break Link given the group unlinks them. A style +/// applied through the group links its lines and labels, and the graph keeps their look, not the link, when it is drawn +/// again. +#[test] +fn graphic_style_links_given_the_axes_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id; + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(axes).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let axes_now = |s: &Session| group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let members = |s: &Session| -> Vec<(Paint, Option)> { + axes_now(s).children().unwrap().iter().map(|c| (c.appearance.fill_paint(), c.extras().graphic_style)).collect() + }; + let g = axes_now(&s); + assert!(g.appearance.items.is_empty() && g.extras().graphic_style.is_none(), "the group is cleared and unlinked"); + assert!(members(&s).iter().all(|m| *m == (green.clone(), Some(style.id))), "{:?}", members(&s)); + s.execute("graphicStyle.breakLink", &json!({"ids": [axes_now(&s).id.0]})).unwrap(); + assert!(members(&s).iter().all(|m| m.1.is_none()), "unlinked"); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes_now(&s).id.0]})).unwrap(); + assert!(members(&s).iter().all(|m| m.1 == Some(style.id)), "linked"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(members(&s).iter().all(|m| *m == (green.clone(), None)), "{:?}", members(&s)); +} + +/// The Appearance commands given a radar graph's Axes group reach its spokes and rings, which keep the edit apart. +#[test] +fn a_style_given_a_radar_graphs_axes_group_is_kept_for_spokes_and_rings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id; + let (_, blue) = blue_style(&mut s, "Blue", false); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes.0]})).unwrap(); + let kept = spec(&s, id).label_styles; + let fill = |rows: Option| rows.and_then(|r| r.paint.fill); + assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "spokes"); + assert_eq!(fill(kept.ring_rows), Some(blue.clone()), "rings"); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0.is_empty()), "the style has no stroke: {looks:?}"); +} + +/// Default Fill and Stroke on an axis line that already shows the default paint is kept for every axis line, in place of +/// the stroke the kind keeps from another line, and leaves the object opacity the kind keeps from another line. +#[test] +fn default_fill_and_stroke_on_an_axis_line_that_shows_it_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [lines[1].id.0], "opacity": 50})).unwrap(); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the 1 pt black default stroke: {looks:?}"); + assert!(looks.iter().all(|l| (l.2 - 0.5).abs() < 1e-6), "the kind keeps its 50% opacity: {looks:?}"); +} + +/// A stroke paint written to an axis line that already shows it is kept for every axis line, in place of the stroke the +/// kind keeps from another line. +#[test] +fn a_stroke_written_to_an_axis_line_that_shows_it_is_kept() { + let cases = [("paint.setStroke", json!({"color": "#000000"})), ("addon.color.fillToStroke", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setFill", &json!({"ids": [lines[1].id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#000000"), "{cmd}: {looks:?}"); + }); +} + +/// A stroke added to an axis line whose stroke shows the paint the new one takes is kept for every axis line, in place of +/// the stroke the kind keeps from another line. +#[test] +fn a_stroke_added_to_an_axis_line_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + s.execute("appearance.addStroke", &json!({"ids": [lines[1].id.0]})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the added 1 pt black stroke: {looks:?}"); +} + +/// An Eyedropper pick of the stroke color, weight or transparency alone onto an axis line that already shows what it +/// writes is kept for every axis line, in place of what the kind keeps from another line. +#[test] +fn an_eyedropper_pick_an_axis_line_already_shows_is_kept() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let cases = [("color", json!({"color": "#ff0000"})), ("weight", json!({"weight": 2})), ("transparency", json!({"opacity": 40}))]; + every_case(cases, |(attr, edit)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [rect.0], "weight": 0.5})).unwrap(); + let lines = line_nodes(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([lines[0].id.0]); + match *attr { + "color" => s.execute("paint.setStroke", &p), + "weight" => s.execute("stroke.set", &p), + _ => { + p["index"] = json!(stroke_row(&lines[0])); + s.execute("appearance.setItem", &p) + } + } + .unwrap(); + let shown = line_nodes(&s, id)[1].clone(); + assert_eq!(line_look(&shown), ("#000000".into(), 0.5, 1.0), "{attr}: the other lines show the default until the graph is drawn again"); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let mut stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + stroke[*attr] = json!(true); + let apply = json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{attr}: {looks:?}"); + let opacities: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{attr}: {opacities:?}"); + }); +} + +/// A stroke color, weight or opacity set with `appearance.setItem`, or a weight set with `stroke.set`, on an axis line +/// that already shows it is kept for every axis line, in place of what the kind keeps from another line. +#[test] +fn a_row_attribute_set_on_an_axis_line_that_shows_it_is_kept() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let cases = [ + ("appearance.setItem", json!({"color": "#ff0000"}), json!({"color": "#000000"})), + ("appearance.setItem", json!({"weight": 2}), json!({"weight": 0.5})), + ("appearance.setItem", json!({"opacity": 40}), json!({"opacity": 100})), + ("stroke.set", json!({"weight": 2}), json!({"weight": 0.5})), + ]; + every_case(cases, |(cmd, kept, shown)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + for (line, values) in [(&lines[0], kept), (&lines[1], shown)] { + let mut p = values.clone(); + p["ids"] = json!([line.id.0]); + if *cmd == "appearance.setItem" { + p["index"] = json!(stroke_row(line)); + } + s.execute(cmd, &p).unwrap(); + } + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{cmd} {shown}: {looks:?}"); + let opacities: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{cmd} {shown}: {opacities:?}"); + }); +} + +/// `appearance.setItem` of a row's opacity alone on an axis line keeps the blend mode the kind keeps from another line, +/// and of its blend mode alone the opacity; a null weight or opacity writes nothing and adds no undo step. +#[test] +fn a_row_attribute_set_on_an_axis_line_keeps_the_others_its_kind_keeps() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let row = |n: &vectorcraft_doc::Node| { + let it = &n.appearance.items[stroke_row(n)]; + (it.opacity(), it.blend()) + }; + let cases = [ + (json!({"blend": "multiply"}), json!({"opacity": 100}), (1.0, BlendMode::Multiply)), + (json!({"opacity": 40}), json!({"blend": "normal"}), (0.4, BlendMode::Normal)), + ]; + every_case(cases, |(kept, shown, want)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + for (line, values) in [(&lines[0], kept), (&lines[1], shown)] { + let mut p = values.clone(); + p["ids"] = json!([line.id.0]); + p["index"] = json!(stroke_row(line)); + s.execute("appearance.setItem", &p).unwrap(); + } + redrawn_line_looks(&mut s, id); + let rows: Vec<(f32, BlendMode)> = line_nodes(&s, id).iter().map(row).collect(); + assert!(rows.iter().all(|r| *r == *want), "{shown}: {rows:?}"); + }); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for key in ["weight", "opacity"] { + let mut p = json!({"ids": [lines[1].id.0], "index": stroke_row(&lines[1])}); + p[key] = serde_json::Value::Null; + s.execute("appearance.setItem", &p).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a null value adds no undo step"); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000")); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 1ab0e0b670..ae07e1c860 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -133,7 +133,7 @@ pub fn specs() -> Vec { "Crop Image", ["Object"], None, - "{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}", + "{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}", has_image, crop_image ), @@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData { PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true)) } -/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and -/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or -/// `r` not on the pixel grid), so the caller draws it instead. -fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec, u32, u32, Affine)> { +/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when +/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel +/// grid), so the caller draws it instead. +fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> { let blob = doc.images.get(&im.key)?; let [a, b, c, d, _, _] = im.xf.as_coeffs(); if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 { @@ -996,9 +996,85 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op return None; } let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image(); + Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) +} + +/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as +/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive +/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as +/// Rasterize's. +fn crop_resolution(p: &Value, im: &ImageObject) -> Result> { + const C: &str = "object.cropImage"; + let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) }; + let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?; + if !(1.0..=2400.0).contains(&ppi) { + return Err(bad(C, "ppi must be between 1 and 2400")); + } + let (_, max) = vectorcraft_tools::cropimage::image_ppi(im); + if ppi > max + 1e-6 { + let max = (max * 100.0 + 1e-6).floor() / 100.0; + return Err(bad(C, format!("ppi can't be more than {max} for this image"))); + } + // An image whose pixels are not square is resampled on both sides, even at its denser side's resolution. + Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6)))) +} + +/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and +/// no side past the renderer's). +fn check_crop_size(w: f64, h: f64) -> Result<()> { + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > MAX_PIXELS || w > side || h > side { + let (w, h) = (w as u64, h as u64); + return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw"))); + } + Ok(()) +} + +/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully +/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in +/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when +/// the working copies would not fit ([`check_resample_size`]). +fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result { + check_resample_size(img.width(), img.height(), w, h)?; + let mut pre = image::ImageBuffer::, Vec>::new(img.width(), img.height()); + for (d, s) in pre.pixels_mut().zip(img.pixels()) { + let a = u32::from(s[3]); + for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) { + // c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted. + *dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16; + } + d.0[3] = (a * 257) as u16; + } + let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3); + let mut res = image::RgbaImage::new(out.width(), out.height()); + for (d, s) in res.pixels_mut().zip(out.pixels()) { + let a = u64::from(s[3]); + for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) { + // c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a. + *dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; + } + d.0[3] = ((a + 128) / 257).min(255) as u8; + } + Ok(res) +} + +/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and +/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes +/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`). +pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> { + let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h)); + let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12)); + if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC { + return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample"))); + } + Ok(()) +} + +/// `img` as PNG bytes. +fn encode_png(img: &image::RgbaImage) -> Result> { let mut png = Vec::new(); - cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; - Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0))))) + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?; + Ok(png) } fn crop_image(s: &mut Session, p: &Value) -> Result { @@ -1014,9 +1090,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; if switch_or(p, "trim", false, C)? { + if p.get("ppi").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi")); + } return trim_image(s, id, (**im).clone()); } let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; + let asked = crop_resolution(p, im)?; + // The resolution the image's pixels are resampled to when they are cut straight. + let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t)); let rect = match p.get("rect").filter(|v| !v.is_null()) { Some(Value::Array(a)) if a.len() == 4 => { let v: Vec = a.iter().filter_map(Value::as_f64).collect(); @@ -1038,16 +1120,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { if r.width() <= 0.0 || r.height() <= 0.0 { return Err(bad(C, "crop rectangle doesn't overlap the image")); } - if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 { + // A box over the whole image still resamples it to a new resolution. + let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6; + // A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image. + let [_, xb, xc, _, _, _] = im.xf.as_coeffs(); + let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9; + if whole && target.is_none() && (asked.is_none() || !turned) { return Err(bad(C, "nothing to crop")); } - // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled. - if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) { - put_pixels(s, id, png, cw, ch, xf)?; + if let Some(t) = target { + check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?; + } + // A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a + // resolution is asked for. + if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) { + let (cut, xf) = match target { + Some(t) => { + let (cw, ch) = cut.dimensions(); + let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); + let resized = resize_premultiplied(&cut, w, h)?; + (resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h))) + } + None => (cut, xf), + }; + let (cw, ch) = cut.dimensions(); + put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?; return Ok(json!({ "id": id.0, "width": cw, "height": ch })); } - // Keep the image's pixel density. - let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); + // A drawn crop is made at a resolution asked for even when it is the image's own: the box of a + // turned or skewed image holds fewer of its pixels a point than the image does. + let target = asked.map(|(t, _)| t); + if let Some(t) = target { + check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?; + } + // Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more + // than the image's own, measured on its pixel grid however it is turned, nor past the size a + // drawing may have), and resampled to it. + let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9)); + let scale = target.map_or(native, |t| { + let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9)); + (2.0 * t).min(own).min(budget).max(t.min(own)) + }); let mut bare = node.clone(); bare.opacity = 1.0; bare.blend = Default::default(); @@ -1058,23 +1173,41 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { if let Some(e) = bare.extras_if_any() { e.color_mask = None; } + let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0)); + let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale); + // At a resolution asked for, the drawing is fitted to the box below: the image is stretched + // about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn. + if target.is_some() + && let NodeKind::Image(bi) = &mut bare.kind + { + let o = r.origin().to_vec2(); + bi.xf = Affine::translate(o) + * Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height()) + * Affine::translate(-o) + * bi.xf; + } let tmp = isolated_doc(&st.doc, vec![bare]); - let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale); let (png, w, h, warning) = render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?; + // At a resolution asked for, the drawing is resampled to the box's size at that resolution and + // fitted to the box, so the image keeps its size. + let (png, w, h, xf) = match target { + Some(t) => { + let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8(); + // Only the decoded pixels are held while they are resampled. + drop(png); + let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32); + let resized = resize_premultiplied(&drawn, tw, th)?; + let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th)); + (encode_png(&resized)?, tw, th, xf) + } + None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)), + }; s.edit("Crop Image", |d, _| { let key = unique_key(d, "crop"); d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png)); if let Some(n) = d.node_mut(id) { - n.kind = NodeKind::Image(Box::new(ImageObject { - key, - width: w, - height: h, - xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale), - link: None, - placement: Default::default(), - pixels: None, - })); + n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None })); } Ok(()) })?; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 3ea501c775..dae66f1a1b 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -251,7 +251,7 @@ pub fn specs() -> Vec { "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind", has_doc, set_props ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index a8bb12b429..8d2a344ffe 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -166,15 +166,18 @@ const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9; /// (while it is edited, the art snaps as the editing layer is written back to it). Every instance /// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a /// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included. -/// An instance in another symbol's art is placed by that symbol's instances and is left as it is. -/// A document without pixel-aligned symbols is not walked. +/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by +/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked. fn refresh_symbols(before: &Document, doc: &mut Document) { let aligned = doc.pixel_aligned_symbols(); if aligned.is_empty() { return; } let was = before.pixel_aligned_symbols(); + // The symbol whose editing mode this edit ended, if any. let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned); let mut every = false; for name in &aligned { let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); @@ -184,22 +187,29 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { _ => true, }; let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name); - if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed { + if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed { snap_symbol_art(doc, name); every = true; } } let natural: HashMap = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + // The symbol editing layer holds another symbol's art. + let editing = doc.symbol_edit.as_ref().map(|e| e.layer); if every { for layer in doc.layers.iter_mut() { - if holds_instance(layer, &natural) { + if Some(layer.id) != editing && holds_instance(layer, &natural) { snap_instances_in(Arc::make_mut(layer), &natural); } } return; } let (mut ids, mut masked) = (vec![], vec![]); - changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + if let Some(layer) = editing { + let outside = |layers: &[Arc]| layers.iter().filter(|l| l.id != layer).cloned().collect::>(); + changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked); + } else { + changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + } for id in ids { if let Some(n) = doc.node_mut(id) { snap_instance(n, &natural); @@ -358,9 +368,10 @@ fn snap_mask(n: &mut Node) -> bool { /// Move symbol instance `n` to whole points when its transform places its symbol's art at the /// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled, -/// rotated (a half turn included) or sheared instance stays where it is. +/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any +/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it. fn snap_instance(n: &mut Node, natural: &HashMap) { - let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return }; + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return }; let Some(nat) = natural.get(symbol.as_str()) else { return }; let [a, b, c, d, e, f] = xf.as_coeffs(); let [na, _, _, nd, _, _] = nat.as_coeffs(); @@ -373,7 +384,12 @@ fn snap_instance(n: &mut Node, natural: &HashMap) { return; } let (x, y) = (e.round(), f.round()); - if x != e || y != f { + if x == e && y == f { + return; + } + n.transform(Affine::translate((x - e, y - f)), Scaling::default()); + // Whole points exactly, which adding the offset to the old position need not give. + if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind { *xf = Affine::new([a, b, c, d, x, y]); } } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 967cf693a6..e72b5b76fb 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, swap ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (for a fill or stroke item, a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `item` needs `aligned` and is a row of the backmost one), the graph stores that object's opacity and blend mode for every label or line of its kind, and with `item` its topmost visible fill and stroke rows too", has_doc, transparency ), @@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -655,6 +655,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) }, |before, d, changed| { let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow()); + // A graph line keeps the paint written to it, also when it already showed it. + let lines = super::graph::capture_line_paint_writes(d, &written.borrow()); let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| { if fill { st.fill = unplaced(&paint); @@ -665,7 +667,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) st.stroke = unplaced(&paint); } }); - Ok(series || labels) + Ok(series || lines || labels) }, )?; // Rejected edits leave the next shape's appearance and active proxy untouched. @@ -1011,7 +1013,7 @@ fn swap(s: &mut Session, p: &Value) -> Result { } // The swap writes the paint of the topmost fill and stroke, not their opacity. let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); + let labels = super::graph::capture_label_changes(&before, d, &ids, false, None); Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) })?; } @@ -1047,8 +1049,15 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); - Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) + // The graph keeps the default paint for every label of a kind it reached, and the default fill and stroke rows + // for every line of a kind it reached, also when one already showed them; the object opacity a line kind keeps + // stays. + let labels = super::graph::capture_label_styles(d, &ids, &|st| { + st.fill = Paint::solid(Color::BLACK); + st.stroke = Paint::None; + }); + let lines = super::graph::capture_line_fill_stroke_rows(d, &ids); + Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines)) })?; } super::newart::reset(s); @@ -1269,6 +1278,9 @@ fn transparency(s: &mut Session, p: &Value) -> Result { }; // Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level. let item_ids = if editing_mask { ids } else { row_targets(s, p, C)? }; + if !editing_mask { + super::appearance::check_part_rows(s, p, aligned || !explicit, C)?; + } // The art of a graph design whose stack an explicit aligned item is a row of goes first: appearance.setItem leaves // it as it is and matches the other objects' rows against it. let of = if editing_mask || !explicit { None } else { super::appearance::design_reference(s, p, C)? }; diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6c7be12540..c15ef6d0c4 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -63,6 +63,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pathtools.shape.set", "addon.pathtools.slideAnchor", "addon.pathtools.smooth", + "addon.pathtools.tangentCircle", "addon.pathtools.trim", "addon.pen.append", "addon.pen.close", @@ -703,8 +704,9 @@ pub(super) const ALLOWED: &[&str] = &[ ]; /// Commands a plug-in may not call although no rule refuses them, in order: they change the -/// preferences, a tool's options, a drag's state or the font names the whole app knows, run -/// plug-ins again, or read a file and report where it is on disk. +/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the +/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and +/// report where it is on disk. pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", @@ -717,5 +719,6 @@ pub(super) const DENIED: &[&str] = &[ "object.pathfinder.options", "stroke.arrowheads.edit", "stroke.arrowheads.list", + "text.similarFonts", "type.compositeFonts.set", ]; diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index 5f412e080d..aaaef531bf 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 { (doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0) } -/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone -/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its -/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out -/// of the image, which then only holds what the effects add around it (a shadow to go under the -/// vector object). The document's raster effects settings add room around it and finish its pixels. -/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not -/// positive, or when its PNG can't be encoded. -pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option { +/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or +/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints +/// nothing, when the area it covers overflows `f64` or the scale is not positive. +fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> { // What it paints (its members' effects included), and how far its fills' and strokes' raster // effects reach beyond that. - let b = vectorcraft_render::painted_bounds(out, whole)?; - let look = out.raster_effects.clone(); - let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around; + let b = vectorcraft_render::painted_bounds(d, whole)?; + let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around; let b = b.inflate(reach, reach); // An area too large for f64 gives a zero scale and an image transform that is not finite. let area = b.width() * b.height(); @@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N return None; } let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + Some((region, scale)) +} + +/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone +/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its +/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out +/// of the image, which then only holds what the effects add around it (a shadow to go under the +/// vector object). The document's raster effects settings add room around it and finish its pixels. +/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not +/// positive, or when its PNG can't be encoded. +pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option { + let (region, scale) = effect_region(out, whole, scale)?; + let look = out.raster_effects.clone(); // Anti-alias off: hard edges (the effects themselves stay smooth). let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None }; let mut img = render(out, vec![whole.clone()], region, scale, anti_alias); @@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo if !below && let Some(image) = rasterize_effect_image(d, n) { return Some(image); } + let whole = effect_art(n, below, members); + let bare = below.then(|| { + let mut b = whole.clone(); + strip_raster(&mut b, false); + b + }); + effect_image(d, &whole, bare.as_ref(), image_scale(d, n)) +} + +/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`: +/// `n` without its transparency, a group's or layer's members without their raster effects when +/// both are set. +fn effect_art(n: &Node, below: bool, members: bool) -> Node { let mut whole = n.clone(); (whole.opacity, whole.blend) = (1.0, Default::default()); whole.extras_mut().mask = None; @@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo strip_raster(Arc::make_mut(c), true); } } - let bare = below.then(|| { - let mut b = whole.clone(); - strip_raster(&mut b, false); - b - }); - // A Rasterize effect at a finer resolution than the document's is rendered at its own. - let scale = raster_fx(n) - .iter() - .filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }) - .fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0)); - effect_image(d, &whole, bare.as_ref(), scale) + whole +} + +/// Pixels per point of the image of the raster effects of `n`: the document's raster effects +/// resolution, or a Rasterize effect's finer one, which is rendered at its own. +fn image_scale(d: &Document, n: &Node) -> f64 { + raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0)) +} + +/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below` +/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the +/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]); +/// 0 when it paints nothing. +pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 { + if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) { + // Measured as Object › Rasterize measures it. + let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0; + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| { + let b = b.inflate(r.add_around, r.add_around); + ((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0)) + }); + // Past Object › Rasterize's limits that image is not made, and the effect's image is. + if let Some((w, h)) = size + && w * h <= super::menucmds::MAX_PIXELS + && w <= side + && h <= side + { + return (w * h) as u64; + } + } + effect_region(d, &effect_art(n, below, members), image_scale(d, n)) + .map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64) } /// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when @@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo /// the image is made of the art before them and moved by them, as the canvas draws it. `None` /// otherwise, when those Transform effects flatten the image, or when the image can't be made. fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option { - let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None }; - let staged = vectorcraft_render::rasterize_stage(d, n); - if let Some((_, map)) = &staged - && !(map.determinant().is_finite() && map.determinant().abs() > 1e-12) - { - return None; - } - let n = staged.as_ref().map_or(n, |(stage, _)| stage); - let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?; + let (whole, r, map) = rasterize_effect_art(d, n)?; let p = json!({ "ppi": r.ppi.unwrap_or(d.raster_effects_ppi), "colorModel": r.color_model.id(), @@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option { "clippingMask": r.clipping_mask, "addAround": r.add_around, }); - let mut whole = n.clone(); - whole.appearance.effects.remove(at); - (whole.opacity, whole.blend) = (1.0, Default::default()); - whole.extras_mut().mask = None; // shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the // image's transparency would need one too; upgrade when CMYK images carry alpha. let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?; let mut image = image.into_node(d); - if let Some((_, map)) = staged { + if let Some(map) = map { image.transform(map, false); } Some(image) } +/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects +/// that move the image, without the Rasterize effect and without its transparency; that effect's +/// options; and the map those Transform effects move the image by. `None` when `n` has another +/// raster effect, when the Rasterize effect is not its own, or when those Transform effects +/// flatten the image. +fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option)> { + let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None }; + let staged = vectorcraft_render::rasterize_stage(d, n); + if let Some((_, map)) = &staged + && !(map.determinant().is_finite() && map.determinant().abs() > 1e-12) + { + return None; + } + let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map))); + let n = stage.as_ref().unwrap_or(n); + let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?; + let mut whole = n.clone(); + whole.appearance.effects.remove(at); + (whole.opacity, whole.blend) = (1.0, Default::default()); + whole.extras_mut().mask = None; + Some((whole, r, map)) +} + /// `v` (an object without its raster effects) replaced by `image` of the object with them: the /// image takes its place with its id, name and transparency (a layer keeps the image as its only /// member). diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index e85117b4ac..12a9dbf12b 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 35d1a12774..cd8b4890f2 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -7,17 +7,20 @@ //! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All //! (`text.spelling.ignoreAll`) skips a word in the active document only. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use std::sync::atomic::{AtomicU64, Ordering}; use craft_proof::{IssueKind, Options, ProofLang}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject}; +use vectorcraft_text::edit; use super::menucmds::whole_or; +use super::textedit::text_mut; +use super::typecmd::refresh_bounds; use super::typemenu::{all_texts, text_ids}; -use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; +use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param}; /// Most unknown words one check lists; past it the result says `more`. pub const MAX_WORDS: usize = 10_000; @@ -36,10 +39,19 @@ pub fn specs() -> Vec { "Check Spelling", [], None, - "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one", + "{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one", has_doc, check ), + cmd!( + "text.spelling.change", + "Change All", + [], + None, + "{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}", + has_doc, + change_words + ), cmd!( query "text.spelling.suggest", "Spelling Suggestions", @@ -107,22 +119,42 @@ pub fn specs() -> Vec { } /// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked -/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them. +/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at +/// `from` when it is given. fn check(s: &mut Session, p: &Value) -> Result { const C: &str = "text.spelling.check"; // Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than // a check of the whole document. - let ids = match p.get("ids").filter(|v| !v.is_null()) { + let mut ids = match p.get("ids").filter(|v| !v.is_null()) { Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)), None => all_texts(&s.doc()?.doc), }; + let max = whole_or(p, "max", MAX_WORDS as u64, C)?; + let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?; let st = s.doc()?; + // Where the last check stopped: the objects before it are skipped, and the bytes of its object + // before `byte`. + let mut from_byte = 0; + if let Some(from) = p.get("from").filter(|v| !v.is_null()) { + let (id, byte) = from_param(from, C)?; + let Some(pos) = ids.iter().position(|i| i.0 == id) else { + return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked"))); + }; + let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else { + return Err(bad(C, format!("`from.id` {id} is not a type object"))); + }; + let len = t.plain_text().len(); + from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?; + ids.drain(..pos); + } let mut words = vec![]; let mut more = false; for id in ids { let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue }; let text = t.plain_text(); - let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len()); + // Only the first object listed starts part way. + let from = std::mem::take(&mut from_byte); + let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len()); for m in found { let Some(word) = text.get(m.range.clone()) else { continue }; words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() })); @@ -135,6 +167,87 @@ fn check(s: &mut Session, p: &Value) -> Result { Ok(json!({ "words": words, "more": more })) } +/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers. +fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> { + let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) { + return Err(bad(command, format!("`from` takes id and byte, not `{k}`"))); + } + let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?; + let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?; + Ok((id, byte)) +} + +/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words +/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out +/// once at the end rather than once for each word. +fn change_words(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.spelling.change"; + let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string(); + let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?; + let mut by_id: BTreeMap> = BTreeMap::new(); + for w in list { + let (id, start, end) = word_param_range(w, C)?; + by_id.entry(NodeId(id)).or_default().push((start, end)); + } + // Every word checked against its object before anything changes. + let st = s.doc()?; + for (id, ranges) in &mut by_id { + let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { + return Err(bad(C, format!("{} is not a type object", id.0))); + }; + let text = t.plain_text(); + ranges.sort_unstable(); + let mut last_end = 0; + for &(a, b) in ranges.iter() { + if a >= b || text.get(a..b).is_none() { + return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0))); + } + if a < last_end { + return Err(bad(C, format!("words of {} overlap at byte {a}", id.0))); + } + last_end = b; + } + // A word that already reads as `to` is left alone, so a list of only those makes no edit. + ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str())); + } + by_id.retain(|_, ranges| !ranges.is_empty()); + let changed: usize = by_id.values().map(Vec::len).sum(); + if changed == 0 { + return Ok(json!({ "changed": 0 })); + } + s.edit("Change All", |d, _| { + for (id, ranges) in &by_id { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + for &(a, b) in ranges.iter().rev() { + // Paragraph styles and ruby follow each edit, as in `text.editRange`. + t.splice_paras(a, b, &to); + edit::replace_range(&mut t.runs, a, b, &to); + t.ruby_after_replace(a, b, to.len()); + } + refresh_bounds(t); + } + Ok(()) + })?; + Ok(json!({ "changed": changed })) +} + +/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers. +fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> { + let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) { + return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`"))); + } + let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?; + let byte = |k: &str| { + o.get(k) + .and_then(Value::as_u64) + .and_then(|b| usize::try_from(b).ok()) + .ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number"))) + }; + Ok((id, byte("start")?, byte("end")?)) +} + /// One word of a type object its dictionaries don't know ([`misspellings`]). #[derive(Clone, Debug, PartialEq)] pub struct Misspelling { @@ -149,6 +262,13 @@ pub struct Misspelling { /// All words). At most `max` of them; the flag says the list was cut short there. What /// `text.spelling.check` lists for one object, and what Auto Spell Check underlines. pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> (Vec, bool) { + misspellings_from(t, ignored, 0, max) +} + +/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at +/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since +/// craft-proof reads a paragraph's language from all of it. +pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet, from: usize, max: usize) -> (Vec, bool) { let text = t.plain_text(); // Each run in its own language, at its bytes of the plain text. let mut spans: Vec<(Range, ProofLang)> = Vec::with_capacity(t.runs.len()); @@ -166,6 +286,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> ( let mut para_start = 0; for para in text.split('\n') { let para_end = para_start + para.len(); + // No word of a paragraph that ends at `from` starts there or later. + if para_end <= from { + para_start = para_end + 1; + continue; + } let para_spans: Vec<(Range, ProofLang)> = spans .iter() .filter_map(|(r, lang)| { @@ -178,6 +303,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet, max: usize) -> ( continue; } let (start, end) = (para_start + issue.start, para_start + issue.end); + if start < from { + continue; + } let Some(word) = text.get(start..end) else { continue }; if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) { continue; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 7cfa020a12..e8fb1349c3 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind (docs/mcp.md) → {objects}", + "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), @@ -307,8 +307,10 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { } }; let of = super::appearance::reference_of(s, p, item, C)?; - // The objects counted: with a design's art, those with a row equal to the art's. - let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| { + // The objects counted: with a design's art, those with a row equal to the art's. A graph line keeps the weight + // given to it, also when it already showed it. + let writes = super::graph::RowWrites { weight: change.weight.is_some(), ..super::graph::RowWrites::NONE }; + let ids = super::appearance::edit_items_writing(s, &ids, item, of, C, "Stroke", false, writes, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 86019048f8..5780e65ed8 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "New Graphic Style", ["Window", "Graphic Styles"], None, - "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}", + "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it, and a graph's Axes or Legend group with none of these for its topmost line or label; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}", has_doc, style_new ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {name}", + "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Break Link to Graphic Style", ["Window", "Graphic Styles"], None, - "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it", + "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it, a graph's Axes group for the group and its lines and labels, and its Legend group for the group and its labels", has_doc, style_break_link ), @@ -364,6 +364,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); let kinds = (shows(true), shows(false)); super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false, false); + // A label or graph line keeps its new rows of those kinds for its kind. The other kind, the object opacity and + // the blend mode stay as the kind keeps them. + super::graph::capture_label_kind_rows(d, &ids, kinds, false); } else { d.graphic_style_id(i); let g = d.graphic_styles[i].clone(); @@ -373,9 +376,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { } super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); + // A label or graph line keeps its new rows for its kind. + super::graph::capture_label_rows(d, &ids); } - // A label keeps its new rows for its kind of label. - super::graph::capture_label_rows(d, &ids); Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index c3fc9a4392..77266b5aaa 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) { None => return Ok(()), Some(b) => match art_of(before) { - Some(old) if same(&old) => return Ok(()), + // Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped. + Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()), old => (old.unwrap_or_default(), b.group), }, }; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 3e8a7e163b..e560c831cd 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -516,6 +516,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option vectorcraft_color::Paint { + let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); + with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill) +} + /// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None` /// when they don't pass its checks. pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map) -> Option> { diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index cb1366ed40..c239cf040e 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -1038,7 +1038,17 @@ fn set_style(s: &mut Session, p: &Value) -> Result { // not in a scaled label's own units). let mut labels_changed = false; if range.is_none() { - labels_changed = super::graph::capture_label_styles(d, &ids, &|st| { + let gives_character = font.is_some() + || style.is_some() + || size.is_some() + || leading.is_some() + || tracking.is_some() + || fill.is_some() + || stroke.is_some() + || !stroke_weight.is_empty() + || features.is_some() + || feature_changes.as_ref().is_some_and(|c| !c.is_empty()); + let change = |st: &mut vectorcraft_doc::CharStyle| { if let Some(f) = &font { st.font_family = f.clone(); st.font_version = None; @@ -1079,7 +1089,13 @@ fn set_style(s: &mut Session, p: &Value) -> Result { if let Some(c) = &feature_changes { st.features = super::textedit::change_features(&st.features, c); } - }); + }; + // A command that gives character attributes keeps the style even when they equal the labels' own. + labels_changed = if gives_character { + super::graph::capture_label_styles_given(d, &ids, &change) + } else { + super::graph::capture_label_styles(d, &ids, &change) + }; } Ok(((), labels_changed)) })?; diff --git a/crates/engine/src/cmd/typecmd/noop_tests.rs b/crates/engine/src/cmd/typecmd/noop_tests.rs index 02481d8bee..b4f5cb2099 100644 --- a/crates/engine/src/cmd/typecmd/noop_tests.rs +++ b/crates/engine/src/cmd/typecmd/noop_tests.rs @@ -102,6 +102,34 @@ fn a_kept_graph_label_style_change_alone_records_one_undo_step() { records_nothing(&mut s, "text.setStyle", p); } +/// `text.setStyle` on a graph label with only `justify`, which the label already has, records no undo step and keeps no +/// character style for its kind of label. +#[test] +fn a_justify_only_style_change_on_a_graph_label_records_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc = s.doc().unwrap().doc.clone(); + let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap(); + let label = legend + .children() + .unwrap() + .iter() + .find_map(|c| match &c.kind { + NodeKind::Text(t) if t.plain_text() == "2025" => Some(c.id), + _ => None, + }) + .unwrap(); + records_nothing(&mut s, "text.setStyle", json!({"ids": [label.0], "justify": "left"})); + let kept = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone(); + assert!(kept.is_none(), "the legend keeps a style"); +} + /// `text.setText` with the text the type already has records no undo step; new text records one. #[test] fn the_same_text_records_no_undo_step() { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 26403cbbef..4415566d13 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -26,6 +26,9 @@ impl Session { vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); + // Clicks and marquees find paths, compound paths, groups and layers where their geometry + // effects draw them. + vectorcraft_doc::hit::set_drawn_art(vectorcraft_render::effects::preview::drawn_art); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index b09d7fc220..eb77a0ca93 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -5847,9 +5847,10 @@ fn add_image(s: &mut Session, r: &vectorcraft_trace::Raster, xf: Affine) -> Node .unwrap() } -/// The traced paths of an Image Trace object: its children but the image and the seam fills. +/// The traced paths of an Image Trace object: its children but the image and the seam fills' +/// clip group (a trace makes no other clip group). fn traced_paths(n: &Node) -> Vec> { - n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect() + n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_) | NodeKind::Group { clip: true, .. })).cloned().collect() } #[test] @@ -6550,7 +6551,12 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert!(matches!(kids[0].kind, NodeKind::Image(_))); let group = seams(&n).unwrap(); assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths"); - let strokes = group.children().unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }), "{group:?}"); + // The two paths cover the image, so the strokes are clipped to its box. + let (clip, strokes) = group.children().unwrap().split_first().unwrap(); + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + assert!([cb.x0, cb.y0, cb.x1 - 80.0, cb.y1 - 40.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); assert_eq!(strokes.len(), 1); assert_eq!(strokes[0].appearance.fill_paint(), Paint::None); let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) }; @@ -6568,6 +6574,14 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert_eq!(names.len(), 3, "{names:?}"); assert_eq!(names[0], "Edges", "{names:?}"); assert_eq!(n.children().unwrap()[0].id, group.id); + // Above a path, the seam fills' group is refused by name, not as an Auto Grouping group. + let (mut s, _, r) = made("abutting", "imageTrace.make", false); + let g = NodeId(r["id"].as_u64().unwrap()); + let kids = node(&s, g).children().unwrap().clone(); + s.execute("object.arrange.bringToFront", &json!({"ids": [kids[1].id.0]})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().last().map(|c| c.id), Some(kids[1].id)); + let e = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap_err().to_string(); + assert!(e.contains("seam fills") && !e.contains("Auto Grouping"), "{e}"); let (mut s, img, _) = made("abutting", "imageTrace.make", false); assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]); // Make and Expand by color too. @@ -6577,13 +6591,126 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { // Overlapping paths are stacked: no seam fills. let (s, _, r) = made("overlapping", "imageTrace.make", false); assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none()); - // An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale. +} + +/// With white left out, the seam fills are clipped to the image's box within the traced paths' +/// box, so the expanded trace measures as its paths do, also on a turned image. +#[test] +fn image_trace_seam_fills_stay_within_the_traced_paths_box() { + let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned(); + let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) { + (false, _) => [255; 4], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + for xf in [Affine::IDENTITY, Affine::translate((100.0, 100.0)) * Affine::rotate(0.5)] { + let mut s = session(); + add_image(&mut s, &band, xf); + let r = s + .execute( + "imageTrace.makeAndExpand", + &json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}), + ) + .unwrap(); + assert_eq!(r["paths"], 2, "{r}"); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let group = seams(&n).unwrap(); + let clip = &group.children().unwrap()[0]; + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + let paths = n.children().unwrap()[1..].iter().filter_map(|c| c.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(n.geometric_bounds(), Some(paths), "{xf:?}"); + assert!(cb.x0 >= paths.x0 - 1e-9 && cb.y0 >= paths.y0 - 1e-9 && cb.x1 <= paths.x1 + 1e-9 && cb.y1 <= paths.y1 + 1e-9, "{xf:?}: {cb:?}"); + if xf == Affine::IDENTITY { + assert!([cb.x0, cb.y0 - 4.0, cb.x1 - 24.0, cb.y1 - 12.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); + } + } +} + +/// On an image stretched more one way than another, the seam fills are the strokes' outlines in +/// image pixels, filled: on an image stretched 20× across, the one along a horizontal edge covers +/// 0.75 image pixels on each side of it, as on an image scaled alike both ways, and does not reach +/// across the transparent rows above the edge. +#[test] +fn image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge() { + // Red beside blue, the edge between them anti-aliased, on an image stretched 3× across and + // squeezed to half height: the outline is 1.5 pixels (4.5 points) across the vertical edge. + let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| { + let share = (16.4 - f64::from(x)).clamp(0.0, 1.0); + let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8; + [mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255] + }); let mut s = session(); add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5)); let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); - let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); - let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") }; - assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let kids = n.children().unwrap(); + assert_eq!(kids[1].name.as_deref(), Some("Seam Fills")); + let fill = &kids[1].children().unwrap()[1]; + assert_eq!(fill.appearance.stroke_paint(), Paint::None, "{:?}", fill.appearance); + assert_eq!(fill.appearance.fill_paint(), kids[2].appearance.fill_paint(), "the lower path's color"); + let bb = outline(fill).0.bounds().unwrap(); + assert!((bb.width() - 4.5).abs() < 0.05 && bb.y0.abs() < 1e-6 && (bb.y1 - 10.0).abs() < 1e-6, "{bb:?}"); + // Rows 0 to 5 transparent, 5 to 10 red, 10 to 20 blue. + let art = vectorcraft_trace::Raster::from_fn(40, 20, |_, y| match y { + 0..5 => [0, 0, 0, 0], + 5..10 => [200, 30, 30, 255], + _ => [30, 30, 200, 255], + }); + let mut s = session(); + add_image(&mut s, &art, Affine::scale_non_uniform(20.0, 1.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let group = n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned().unwrap(); + let (_, members) = group.children().unwrap().split_first().unwrap(); + assert!(!members.is_empty(), "{group:?}"); + for m in members { + // What the member covers: its outline, grown by half its stroke's width. + let half = m.appearance.items.iter().fold(0.0_f64, |w, it| match it { + AppearanceItem::Stroke(l) => w.max(l.width / 2.0), + _ => w, + }); + let bb = outline(m).0.bounds().unwrap(); + let (y0, y1) = (bb.y0 - half, bb.y1 + half); + assert!(y0 > 9.25 - 1e-6 && y1 < 10.75 + 1e-6, "covers y {y0} to {y1}: {m:?}"); + } + // Renamed, the group of filled outlines is still the seam fills: Expand by color keeps it under + // every color's group. + s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap(); + s.execute("imageTrace.expand", &json!({"id": n.id.0, "byColor": true})).unwrap(); + assert_eq!(node(&s, n.id).children().unwrap()[0].id, group.id); +} + +/// A trace made before the seam fills were clipped holds them in a group without a clip: Expand by +/// color keeps that group under every color's group too, named or renamed. +#[test] +fn image_trace_expand_by_color_keeps_unclipped_seam_fills() { + let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| { + let share = (16.4 - f64::from(x)).clamp(0.0, 1.0); + let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8; + [mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255] + }); + for name in [Some("Seam Fills"), None] { + let mut s = session(); + add_image(&mut s, &art, Affine::scale(2.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + // The seam fills as such a trace holds them: the strokes alone, in a plain group. + let seams = node(&s, g).children().unwrap()[1].clone(); + let NodeKind::Group { clip: true, children } = &seams.kind else { panic!("{seams:?}") }; + let mut legacy = Node::group(seams.id, children[1..].to_vec()); + legacy.name = name.map(Into::into); + s.edit("legacy", |d, _| { + let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("trace group") }; + children[1] = Arc::new(legacy); + Ok(()) + }) + .unwrap(); + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap(); + let kids = node(&s, g).children().unwrap().clone(); + assert_eq!(kids.len(), 3, "{name:?}: {kids:?}"); + assert_eq!(kids[0].id, seams.id, "{name:?}"); + } } /// Expand by color: each color's paths in a group of their own, named by the color, the groups @@ -7646,6 +7773,51 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { } } +/// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills +/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines), renamed +/// too. +#[test] +fn image_trace_outline_view_leaves_out_the_seam_fills() { + // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×, + // or 2× across and 2.5× down. + let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) { + (false, _) => [0, 0, 0, 0], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + for (scale, stretched) in [(Affine::scale(2.0), false), (Affine::scale_non_uniform(2.0, 2.5), true)] { + let mut s = session(); + add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * scale); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + let seams = + node(&s, g).children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })).cloned().expect("seam fills"); + // Strokes, or on the stretched image their outlines, filled. + let members = &seams.children().unwrap()[1..]; + assert!(!members.is_empty()); + for m in members { + let (fill, stroke) = (m.appearance.fill_paint(), m.appearance.stroke_paint()); + assert_eq!((fill != Paint::None, stroke != Paint::None), (stretched, !stretched), "{scale:?}: {fill:?}, {stroke:?}"); + } + s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); + let screen = render_doc(&s, true); + // The image's top edge (y = 50), away from the art: nothing drawn. + for x in [60, 110, 160] { + assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 50)); + } + // The art's left edge (x = 70) is outlined. + assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128), "{scale:?}"); + // Beside the red and blue paths' shared edge (x = 110), inside the seam band (1.5 units + // each side on the stretched image) but off the traced outlines (x = 109 and 110): nothing. + for x in [108, 111] { + assert!(screen.pixel(x, 100)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 100)); + } + // Renamed, the group is still left out: the view draws as it did. + s.execute("layer.setProps", &json!({"id": seams.id.0, "name": "Edges"})).unwrap(); + assert!(render_doc(&s, true).pixels == screen.pixels, "{scale:?}: renamed seam fills drawn"); + } +} + /// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals /// overlapping) merges every region the drags touch into one shape whose outline is only the /// merged area's border: no edge between merged regions stays in, as a stray line or a spur. diff --git a/crates/engine/src/tests/clipflavours.rs b/crates/engine/src/tests/clipflavours.rs index 5955389aea..55e4cdff7f 100644 --- a/crates/engine/src/tests/clipflavours.rs +++ b/crates/engine/src/tests/clipflavours.rs @@ -512,3 +512,21 @@ fn keep_plain_text_preference_drops_pasted_formatting() { assert_eq!(paste_copied_range(false), 40.0, "Keep Formatting"); assert_eq!(paste_copied_range(true), 10.0, "Keep Plain Text"); } + +/// #7975: pasted plain text is new type, filled as [Normal Character Style] is, not with the +/// current fill. +#[test] +fn pasted_plain_text_takes_the_normal_character_style_fill() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "clipboard.importText", json!({"text": "Plain"})); + run(&mut s, "edit.paste", json!({"center": [200, 150]})); + assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, Paint::solid(Color::BLACK)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let attrs = crate::cmd::textstyles::char_attrs(&vectorcraft_doc::CharStyle { fill: blue.clone(), ..Default::default() }); + run(&mut s, "charStyle.setAttrs", json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}})); + run(&mut s, "clipboard.importText", json!({"text": "Plain"})); + run(&mut s, "edit.paste", json!({"center": [200, 150]})); + assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, blue); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index fb4eb55789..54364915da 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -677,16 +677,16 @@ fn the_eraser_tip_varies_with_its_modes() { assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line"); let level_tip = left_of_line(json!([])); assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line"); - // A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed. + // A 1000 pt tip on Tilt erases 1000 pt across with a mouse, as it does on Fixed. let mut s = session(); rect(&mut s, 0.0, 0.0, 4000.0, 4000.0); - let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10}); + let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1000, "sizeMode": "tilt", "sizeVariation": 10}); s.execute("path.eraseRegion", &big).unwrap(); let filled = |x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))); - assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip"); + assert_eq!((filled(2000.0, 2490.0), filled(2000.0, 2510.0)), (false, true), "a 1000 pt tip"); // A Size Variation kept while Size is Fixed leaves the size alone. - let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000})); + let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000})); assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation"); let mut s = session(); let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); @@ -2882,6 +2882,116 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() { s.execute("path.eraseRegion", &sized).unwrap(); } +/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90 +/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six +/// numbers, naming the point; the document, the selection and the undo history stay as they were. +/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw. +#[test] +fn pen_values_outside_their_ranges_are_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let good = [json!([90, 150]), json!([150, 150]), json!([210, 150])]; + let cmds = [ + "path.freehand", + "brush.freehand", + "path.knife", + "path.eraseRegion", + "path.eraseSegments", + "path.smoothRegion", + "path.joinScrub", + "path.blob", + ]; + let pressure = "`pressure` must be from 0 to 1"; + let tilt_x = "`tiltX` must be from -90 to 90"; + let tilt_y = "`tiltY` must be from -90 to 90"; + let rotation = "`rotation` must be from 0 to 360"; + let entries = "`points[3]` must be an array of at most 6 entries"; + for cmd in cmds { + for (bad, want) in [ + (json!([150, 150, -0.01]), pressure), + (json!([150, 150, 1.5]), pressure), + (json!({"x": 150, "y": 150, "pressure": 1e300}), pressure), + (json!([150, 150, 0.5, -90.5]), tilt_x), + (json!([150, 150, 0.5, 91, 0]), tilt_x), + (json!({"x": 150, "y": 150, "tiltX": -1e300}), tilt_x), + (json!([150, 150, null, 0, -1e300]), tilt_y), + (json!({"x": 150, "y": 150, "tiltY": 90.01}), tilt_y), + (json!([150, 150, null, null, null, -1]), rotation), + (json!({"x": 150, "y": 150, "rotation": 360.5}), rotation), + (json!([150, 150, null, null, null, 720]), rotation), + (json!([150, 150, 0.5, 0, 0, 0, 1]), entries), + (json!([150, 150, null, null, null, null, null]), entries), + ] { + let points: Vec<_> = good.iter().cloned().chain([bad]).collect(); + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &json!({"points": points}), want); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {points:?} changed the selection"); + } + } + for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() { + let y = 300.0 + 50.0 * row as f64; + let points = json!([ + [100, y, 0, -90, 90, 0], + [150, y, 1, 90, -90, 360], + [200, y, 0.5, null, 30], + {"x": 250, "y": y, "tiltX": -45, "pressure": null}, + [300, y], + {"x": 350, "y": y, "rotation": 359.99}, + ]); + s.execute(cmd, &json!({"points": points})).unwrap_or_else(|e| panic!("{cmd}: {e}")); + let mouse = json!([[100, y + 20.0], [200, y + 20.0], [300, y + 25.0]]); + s.execute(cmd, &json!({"points": mouse})).unwrap_or_else(|e| panic!("{cmd} with mouse points: {e}")); + } +} + +/// `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt and a `sizeVariation` +/// outside 0 to 1000 pt, in every `sizeMode` each takes and with it left out, and a `sizeVariation` +/// that is not a number with Fixed too; nothing changes. The ends of each range and null still draw. +#[test] +fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let stroke = json!({"points": [[90, 150, 0.2, 30, 0, 45], [150, 150, 0.6, 0, 30, 90], [210, 150, 1, -30, 0, 180]]}); + let size = "`size` must be from 0.1 to 1000"; + let variation = "`sizeVariation` must be from 0 to 1000"; + let blob_modes = [json!(null), json!("fixed"), json!("pressure")]; + let eraser_modes = [json!(null), json!("fixed"), json!("random"), json!("pressure"), json!("tilt"), json!("bearing"), json!("rotation")]; + // The Eraser keeps its own message for a negative Size Variation. + for (cmd, modes, negative) in + [("path.blob", &blob_modes[..], variation), ("path.eraseRegion", &eraser_modes[..], "sizeVariation must be 0 or more")] + { + for x in [json!(0.09), json!(0), json!(-1), json!(1000.5), json!(1e300)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &with(&stroke, json!({"size": x})), size); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} size {x} changed the selection"); + } + for mode in modes { + for (x, want) in [(json!(-0.5), negative), (json!(1000.01), variation), (json!(1e300), variation)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &with(&stroke, json!({"sizeMode": mode, "sizeVariation": x})), want); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {mode} sizeVariation {x} changed the selection"); + } + let text = json!({"sizeMode": mode, "sizeVariation": "8"}); + refuses_with(&mut s, cmd, &with(&stroke, text), "`sizeVariation` must be a number, not \"8\""); + } + } + for (row, (cmd, modes)) in [("path.blob", &blob_modes[..]), ("path.eraseRegion", &eraser_modes[..])].into_iter().enumerate() { + let y = 300.0 + 100.0 * row as f64; + let at = |p: serde_json::Value| with(&json!({"points": [[100, y, 0.2, 30, 0, 0], [200, y, 0.6, 0, 30, 90], [300, y, 1, -30, 0, 360]]}), p); + for extra in [json!({"size": 0.1}), json!({"size": 1000}), json!({"size": null, "sizeVariation": null, "sizeMode": null})] { + s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}")); + } + for mode in modes { + for x in [0, 1000] { + let extra = json!({"sizeMode": mode, "sizeVariation": x}); + s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}")); + } + } + } +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index e4bfa26b2f..0cc0106351 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() { assert!(expandable(&s), "the fill's shadow can be expanded"); run(&mut s, "effect.expandAppearance", json!({})); - let ch = node(&s, id).children().cloned().expect("the instance becomes a group"); + let n = node(&s, id); + let ch = n.children().cloned().expect("the instance becomes a group"); assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label()); - assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label()); - no_effects_left(&ch[1]); + n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance")); + no_effects_left(&n); let after = render(&s); assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); run(&mut s, "edit.undo", json!({})); @@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() { assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100)); } +/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner` +/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new +/// fill without paint on top. Returns the Outer instance and its new row's index. +fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) { + let (inner_id, inner_row) = instance_with_row(s, "Inner", true); + inner(s, inner_id, inner_row); + let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +/// The symbol instances and the images in `n`. +fn instances_and_images(n: &Node) -> (usize, usize) { + let mut found = (0, 0); + n.walk(&mut |part| match part.kind { + NodeKind::SymbolInstance { .. } => found.0 += 1, + NodeKind::Image(_) => found.1 += 1, + _ => {} + }); + found +} + +/// Replace the art of every symbol with an empty group. +fn empty_symbols(s: &mut Session) { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + for (i, sym) in d.symbols.iter_mut().enumerate() { + sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![])); + } +} + +/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art +/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result +/// no longer follows either symbol. +#[test] +fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert!(images >= 1, "the inner shadow is an image"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); + empty_symbols(&mut s); + assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols"); +} + +/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's +/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in +/// one undo step. +#[test] +fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + shadow_row(&mut s, id, row); + let before = render(&s); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert!(images >= 2, "the outer and inner shadows are images: {images}"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); + + run(&mut s, "edit.undo", json!({})); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back"); + run(&mut s, "edit.redo", json!({})); + empty_symbols(&mut s); + assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols"); +} + +/// A blur on the nested instance's fill: the nested instance becomes the image. +#[test] +fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() { + let mut s = session(); + let blur = |s: &mut Session, id: NodeId, row: usize| { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}})); + }; + let (id, row) = nested_with_row(&mut s, blur); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + let (instances, images) = instances_and_images(&n); + assert_eq!(instances, 0, "the outer and inner instances become art"); + assert_eq!(images, 1, "the blurred inner art is one image"); + no_effects_left(&n); + let after = render(&s); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it. +fn blue_backdrop(s: &mut Session) { + run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200})); + run(s, "paint.setFill", json!({"color": "#0000ff"})); +} + +/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`. +fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) { + let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"}); + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params})); +} + +/// The blend modes of the images in `n`, in the order the walk visits them. +fn image_modes(n: &Node) -> Vec { + let mut modes = vec![]; + n.walk(&mut |part| { + if matches!(part.kind, NodeKind::Image(_)) { + modes.push(part.blend); + } + }); + modes +} + +/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below +/// as the shadow did, rather than painting red over it. +#[test] +fn a_nested_instance_multiply_shadow_image_keeps_its_mode() { + let mut s = session(); + blue_backdrop(&mut s); + let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply")); + offset_row(&mut s, id, row, 10.0); + let before = render(&s); + assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art"); + assert_eq!(image_modes(&n), [BlendMode::Multiply]); + no_effects_left(&n); + let after = render(&s); + assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100)); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply. +#[test] +fn an_instance_multiply_shadow_image_keeps_its_mode() { + let mut s = session(); + blue_backdrop(&mut s); + let (id, row) = instance_with_row(&mut s, "Square", true); + red_shadow_row(&mut s, id, row, "multiply"); + let before = render(&s); + assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(image_modes(&n), [BlendMode::Multiply]); + let after = render(&s); + assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100)); + assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24)); +} + +/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it. +#[test] +fn a_hidden_nested_instance_fill_shadow_makes_no_image() { + let mut s = session(); + let hidden = |s: &mut Session, id: NodeId, row: usize| { + shadow_row(s, id, row); + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false})); + }; + let (id, row) = nested_with_row(&mut s, hidden); + offset_row(&mut s, id, row, 10.0); + assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow"); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image"); + no_effects_left(&n); +} + +/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art +/// expands around it. +#[test] +fn a_nested_instance_of_a_missing_symbol_stays_an_instance() { + let mut s = session(); + let (id, row) = nested_with_row(&mut s, shadow_row); + offset_row(&mut s, id, row, 10.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.symbols.retain(|sym| sym.name != "Inner"); + } + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image"); +} + +/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand +/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which +/// the result reports. +#[test] +fn nested_instance_raster_effects_stop_at_the_image_limit() { + let mut s = session(); + // Images of a pixel or two each. + run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1})); + let blur = |s: &mut Session, id: NodeId, row: usize| { + run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}})); + }; + let (id, row) = nested_with_row(&mut s, blur); + offset_row(&mut s, id, row, 10.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap(); + let inner = (*d.symbols[outer].art).clone(); + assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance"); + let copies = (0..1_100) + .map(|_| { + let mut copy = inner.clone(); + copy.id = d.alloc_id(); + std::sync::Arc::new(copy) + }) + .collect(); + d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies)); + } + + let r = run(&mut s, "effect.expandAppearance", json!({})); + assert_eq!(r["rasterLeft"], 76, "{r}"); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}"); + let n = node(&s, id); + assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay"); + n.walk(&mut |part| { + if matches!(part.kind, NodeKind::SymbolInstance { .. }) { + assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur"); + } + }); +} + +/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which +/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was +/// before expanding. +fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node { + // Images of a pixel or two each. + run(s, "document.rasterEffectsSettings", json!({"resolution": 1})); + run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}})); + run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}})); + let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}})); + let before = node(s, id); + let group = { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let blurred = d.node(sq).unwrap().clone(); + d.remove(sq).unwrap(); + let mut members: Vec<_> = (0..1_024) + .map(|_| { + let mut copy = blurred.clone(); + copy.id = d.alloc_id(); + std::sync::Arc::new(copy) + }) + .collect(); + members.push(std::sync::Arc::new(before.clone())); + let group = d.alloc_id(); + *d.node_mut(id).unwrap() = Node::group(group, members); + group + }; + + let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]})); + assert_eq!(r["rasterLeft"], 1, "{r}"); + before +} + +/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance +/// of its symbol, with both effects. +#[test] +fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap()); + let before = adjusted_and_left_by_the_image_limit(&mut s, id); + assert!(matches!(before.kind, NodeKind::SymbolInstance { .. })); + assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur"); +} + +/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is, +/// and the document keeps no recolored copy of its pixels. +#[test] +fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() { + let mut s = session(); + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let images: Vec = s.doc().unwrap().doc.images.keys().cloned().collect(); + let before = adjusted_and_left_by_the_image_limit(&mut s, id); + assert!(matches!(before.kind, NodeKind::Image(_))); + assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur"); + // Besides the squares' images, the document holds the image's pixels alone. + let after: Vec = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect(); + assert_eq!(after, images, "no recolored copy stays in the document"); +} + /// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the /// shadow on the art's fill, not its stroke, and PDF export makes an image of it. #[test] diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 5eb059bd3b..62110be5a2 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -34,6 +34,59 @@ fn the_font_list_names_every_available_family_with_its_styles() { assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err()); } +/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the +/// order the font menus show; bad params are refused. +#[test] +fn similar_fonts_lists_every_family_by_likeness() { + let mut s = Session::new(); + let db = FontDb::global(); + let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap(); + assert_eq!(r["family"], "Source Sans 3"); + let order = names(&r["families"]); + assert_eq!(order.first().map(String::as_str), Some("Source Sans 3")); + let mut sorted = order.clone(); + sorted.sort(); + let mut listed = db.menu_family_list().to_vec(); + listed.sort(); + // Other tests running at the same time add and remove composite fonts; the installed families are compared. + let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::>(); + assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once"); + // The two answers are compared whole when the available fonts did not change while both were + // made (the same `FontDb::generation`), and by their installed families when they changed + // during every try. + let mut answers = (vec![], vec![], false); + for _ in 0..20 { + let generation = db.generation(); + let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]); + let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]); + let unchanged = db.generation() == generation; + answers = (all, two, unchanged); + if unchanged { + break; + } + } + let (all, two, unchanged) = answers; + assert_eq!(two.len(), 2); + if unchanged { + assert_eq!(two, all[..2], "the first families, in order"); + } else { + let (two, all) = (installed_only(&two), installed_only(&all)); + assert_eq!(two[..], all[..two.len()], "the first installed families, in order"); + } + for (params, error) in [ + (json!({}), "`family` is required"), + (json!({"family": " "}), "`family` is required"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "font family `No Such Font` is not available"), + (json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"), + (json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"), + ] { + let e = s.execute("text.similarFonts", ¶ms).unwrap_err().to_string(); + assert!(e.contains(error), "{params}: {e}"); + } +} + #[test] fn refreshing_the_font_list_redraws_type_without_editing_the_document() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6ae474cc8b..ada206784a 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2168,6 +2168,64 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() } } +/// A confined caller's SVG and SVGZ with Preserve Editing Capabilities carry a native document +/// without the Export for Screens folder when it is outside the read roots, with the other export +/// settings and the art; the open document keeps the folder. A folder inside the roots, and any +/// folder without roots, stays in the attachment. +#[test] +fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("svg-export-folder-away"); + let home = Folder::new("svg-export-folder-home"); + let outside = away.0.to_string_lossy().into_owned(); + let inside = home.file("screens"); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + let set_folder = |s: &mut Session, folder: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap(); + }; + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + // The native document an SVG's text carries. + let attached = |text: &str| { + let data = vectorcraft_svg::editing_data(text).expect("editing data"); + vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap() + }; + let check = |d: &Document, folder: Option<&str>, what: &str| { + assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}"); + assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}"); + assert!(d.node(rect).is_some(), "{what}: no art"); + }; + // Every way an SVG is asked for with Preserve Editing, its text and its native document. + let every = |s: &mut Session, confined: bool, folder: Option<&str>| { + let run = |s: &mut Session, cmd: &str, p: Value| { + let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) }; + r.unwrap() + }; + for format in ["svg", "svgz"] { + let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true})); + check(&attached(&svg_text(&r)), folder, &format!("{format} serialize")); + let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}})); + check(&attached(&svg_text(&r)), folder, &format!("{format} options object")); + let path = home.file(&format!("export.{format}")); + run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true})); + let bytes = std::fs::read(&path).unwrap(); + check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export")); + } + }; + set_folder(&mut s, &outside); + every(&mut s, true, None); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str())); + every(&mut s, false, Some(&outside)); + // Without Preserve Editing the SVG carries no native document. + let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap(); + assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}"); + set_folder(&mut s, &inside); + every(&mut s, true, Some(&inside)); +} + /// A confined caller's SVG of a placed document whose art links an image: the file draws that art /// and names the image's file, so a file outside the read roots refuses it and one inside them is /// written. Any output that names no file is written. diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1db3ffa34e..fb836e9099 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1588,6 +1588,235 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() { assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); } +/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size. +#[test] +fn crop_image_resamples_the_cut_to_the_resolution_asked_for() { + let (mut s, img, px) = busy_image_at_two_points_a_pixel(); + // The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image(); + // Resampled in 16 bits a channel: within a level of the 8-bit resampling. + let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3); + assert_eq!(out.dimensions(), want.dimensions()); + assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1)); +} + +/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not +/// tint the partly transparent edge of what is opaque. +#[test] +fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() { + // Opaque white on the left half, fully transparent red on the right. + let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) }); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + // 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear. + s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap(); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent"); + for p in out.pixels().filter(|p| p[3] > 0) { + assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}"); + } +} + +/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest +/// alpha comes out as that color, not black. +#[test] +fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() { + let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1])); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap(); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + for p in out.pixels() { + let near = |a: u8, b: u8| a.abs_diff(b) <= 1; + assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}"); + } +} + +/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its +/// place: the edge of the image's content lands where it was in the box. +#[test] +fn crop_image_between_pixels_keeps_the_content_at_its_place() { + // White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt. + let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) }); + let mut png = Vec::new(); + px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let img = selected(&s)[0]; + s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap(); + // 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into + // the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white. + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8(); + let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::() / f64::from(out.height()); + let want = 49.0 * 79.0 / 101.0; + assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}"); +} + +/// A box between pixels is drawn at the resolution asked for, and lands on the box. +#[test] +fn crop_image_between_pixels_draws_at_the_resolution_asked_for() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}"); + // 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box. + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}"); +} + +/// A box over the whole image with a new resolution resamples it; with the image's own there is +/// nothing to do. +#[test] +fn crop_image_over_the_whole_image_only_resamples_it() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let before = undo_len(&s); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}"); + assert_eq!(undo_len(&s), before); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}"); + assert_eq!(undo_len(&s), before + 1, "one undo step"); + let b = bounds(&s, img); + assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}"); +} + +/// An image scaled more down than across is resampled on both sides at the resolution of its denser +/// side, so its pixels come out square. +#[test] +fn crop_image_resamples_pixels_that_are_not_square() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + // 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt. + s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap(); + let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}"); + let b = bounds(&s, img); + assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}"); +} + +/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one +/// with trim; the image stays as it was. +#[test] +fn crop_image_refuses_a_resolution_it_cannot_give() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + let before = (undo_len(&s), node(&s, img)); + let refused = |s: &mut Session, p: Value, want: &str| { + let r = s.execute("object.cropImage", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + }; + for v in [json!(0), json!(-72), json!("high"), json!(true)] { + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}")); + } + for v in [0.5, 1e-310, 2401.0] { + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400"); + } + refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image"); + refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi"); + assert_eq!((undo_len(&s), node(&s, img)), before); + // A null ppi keeps the image's own, as a missing one does. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}"); +} + +/// A turned image keeps its own resolution as the limit (not the density across its bounding box), +/// and its drawn cut is resampled to the box's size at the resolution asked for. +#[test] +fn crop_image_of_a_turned_image_resamples_its_drawing() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}"); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}"); + let c = bounds(&s, img); + assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}"); +} + +/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower +/// density of the box around it. +#[test] +fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}"); + // Over the whole box around it, its own resolution draws it square to the page. + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let b = bounds(&s, img); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap(); + assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}"); + let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}"); +} + +/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it. +#[test] +fn crop_image_takes_a_linked_image_up_to_300_ppi() { + let (mut s, img, _) = busy_image_at_two_points_a_pixel(); + s.edit("Link", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") }; + im.link = Some(vectorcraft_doc::LinkInfo::new("art.png")); + Ok(()) + }) + .unwrap(); + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}"); + // 72 ppi: a pixel a point. + let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap(); + assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}"); + let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") }; + assert!(im.link.is_none()); +} + +/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and +/// changes nothing. +#[test] +fn crop_image_tool_options_refuse_values_they_cannot_use() { + let (mut s, _, _) = busy_image_at_two_points_a_pixel(); + s.select_tool("cropImage", ViewInfo::default()).unwrap(); + s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap(); + // 72 ppi is above the selected 36 ppi image's own. + for (key, value) in + [("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))] + { + assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}"); + } + let o = s.tool_options(); + assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}"); + s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap(); + assert!(s.tool_options().get("ppi").is_none()); +} + /// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a /// null `rect` crops to the artboard as a missing one does. #[test] @@ -5331,6 +5560,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() { assert!(within.contains("the image's pixels can't be read"), "{within}"); } +#[test] +fn crop_image_resampling_is_held_to_the_raster_allowance() { + use crate::cmd::menucmds::check_resample_size; + let max = crate::cmd::fileio::MAX_RASTER_ALLOC; + // 40 bytes a pixel resampled to the same size (12 + 16 + 12). + let side = ((max / 40) as f64).sqrt() as u32; + assert!(check_resample_size(side, side, side, side).is_ok()); + let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string(); + assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}"); + // A large source counts even when the result is small. + let wide = ((max / 12) as f64).sqrt() as u32 + 1; + assert!(check_resample_size(wide, wide, 1, 1).is_err()); + assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err()); + assert!(check_resample_size(100, 100, 50, 50).is_ok()); +} + #[test] fn crop_image_trim_leaves_a_cmyk_image_alone() { // CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error. diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 1bac01d48d..d89a7eddf3 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -278,6 +278,35 @@ fn each_copys_shadow_expands_as_the_canvas_draws_it() { 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 +/// own 20 pt. +#[test] +fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() { + let mut s = session(); + let t = run(&mut s, "text.create", json!({"x": 20, "y": 60, "text": "I", "size": 40}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [t]})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + 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": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); + let before = render(&s); + if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) { + eprintln!("skipped: built without a font that draws the type"); + return; + } + // The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow. + let red = + (100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0); + let (x, y) = red.expect("the copy"); + assert_eq!(before.pixel(x + 38, y), [0, 255, 0, 255], "the copy's shadow, 40 pt to the right of ({x}, {y})"); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + /// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on /// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide. #[test] diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index b70098d9c9..00b4cce694 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -1436,6 +1436,40 @@ fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() { assert!(whole(&[(e, f)]), "{e} {f}"); } +/// An instance snapped to whole points takes the art of its linked opacity mask along by the same +/// amount, as a move does; the art of an unlinked mask stays where it is. +#[test] +fn an_instance_snapped_to_the_grid_moves_its_linked_mask() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + s.execute("symbol.new", &json!({"name": "Px"})).unwrap(); + let place = |s: &mut Session, x: f64, linked: bool| { + let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) }; + d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask)); + inst + }; + let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false)); + let mask_points = |s: &Session, inst: u64| { + let d = &s.doc().unwrap().doc; + let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap(); + mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::>() + }; + let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked)); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let [.., e0, f0] = xf_before.as_coeffs(); + let [.., e, f] = instance_xf(&s, linked).as_coeffs(); + assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}"); + let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect(); + let after = mask_points(&s, linked); + assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}"); + assert!(whole(&placed_points(&s, unlinked))); + assert_eq!(mask_points(&s, unlinked), unlinked_before); +} + /// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored /// on the pixel grid, so its instances stay on it. #[test] @@ -1459,3 +1493,49 @@ fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() { let pts = placed_points(&s, inst); assert!(whole(&pts), "{pts:?}"); } + +/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid +/// on the editing layer at once, and its instance stays on it after editing ends. +#[test] +fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + let before = points(&s, part); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let xf = d.symbol_edit.as_ref().unwrap().xf; + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect(); + let shown = points(&s, part); + assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); +} + +/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that +/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are. +#[test] +fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [b]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone(); + let shown = instance_xf(&s, inner); + assert!(!whole(&placed_points(&s, inner))); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(instance_xf(&s, inner), shown); + let d = &s.doc().unwrap().doc; + assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art)); +} diff --git a/crates/engine/src/tests/select_effects.rs b/crates/engine/src/tests/select_effects.rs index d2160fba34..5ab9fd1bf8 100644 --- a/crates/engine/src/tests/select_effects.rs +++ b/crates/engine/src/tests/select_effects.rs @@ -1,6 +1,6 @@ //! Clicks, hovers and marquees with the selection tools leave out the area that raster effects //! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the -//! effect, or nothing. +//! effect, or nothing. Clicks and marquees take art where its geometry effects draw it. use serde_json::{Value, json}; use vectorcraft_doc::NodeId; @@ -391,3 +391,107 @@ fn group_selection_hover_over_a_drop_shadow_marks_nothing() { } assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]); } + +/// A rectangle that a Transform effect moves 100 pt to the right is selected by a click and by a +/// marquee where it is drawn, and not at its own place, which it no longer paints. The same holds +/// for a group whose own Transform effect moves it. +#[test] +fn a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 40.0, 40.0, "#ff0000"); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [a.0], "params": {"moveH": 100}, "item": null})); + assert_eq!(pixel(&s, 140, 40), [255, 0, 0, 255], "drawn where it moved"); + assert_eq!(pixel(&s, 40, 40), WHITE, "not drawn at its own place"); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 40.0, 40.0).is_empty()); + assert_eq!(click(&mut s, 140.0, 40.0), [a]); + assert_eq!(press(&mut s, "selection", (110.0, 10.0), (130.0, 30.0), Mods::default()), [a], "a marquee across its drawn corner"); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "selection", (10.0, 10.0), (30.0, 30.0), Mods::default()).is_empty(), "a marquee across its own corner"); + + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [g.0], "params": {"moveH": 100}, "item": null})); + assert_eq!(pixel(&s, 140, 140), BLUE, "the group drawn where it moved"); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 40.0, 140.0).is_empty()); + assert_eq!(click(&mut s, 140.0, 140.0), [g]); + assert_eq!(press(&mut s, "selection", (110.0, 110.0), (130.0, 130.0), Mods::default()), [g]); + run(&mut s, "select.none", json!({})); + assert!(press(&mut s, "selection", (10.0, 110.0), (30.0, 130.0), Mods::default()).is_empty()); +} + +/// A group's own fill paints its member's shape before the member's own Transform effect moves the +/// member: a click there selects the group, and a click on the moved member selects it too. A +/// Direct Selection marquee takes the group there and the member where it moved. +#[test] +fn a_click_selects_a_group_where_its_own_fill_paints_a_moved_member() { + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveH": 100}, "item": null})); + assert_eq!(pixel(&s, 40, 140), [255, 0, 0, 255], "the group's fill at the member's own place"); + assert_eq!(pixel(&s, 140, 140), BLUE, "the member where it moved"); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 40.0, 140.0), [g]); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 140.0, 140.0), [g]); + // A marquee across the edge of the group's fill takes the group, and one across the moved + // member's edge takes the member. + let doc = &s.doc().unwrap().doc; + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]); + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(110.0, 130.0, 130.0, 150.0), None, true), [b]); +} + +/// An inner group's own fill paints its member's shape before the member's own Transform effect +/// moves the member, and so does an outer group's own fill around it: a Direct Selection marquee +/// across the edge of those fills takes both groups, and one across the moved member takes it. +#[test] +fn a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group() { + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let o = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#00ff00"})); + assert_eq!(pixel(&s, 40, 140), [0, 255, 0, 255], "the outer group's fill at the member's own place"); + assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved"); + let doc = &s.doc().unwrap().doc; + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [o, g]); + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]); +} + +/// A group's own fill paints its member's shape before the member's own Transform effect moves +/// the member, and so does its layer's own fill around it: a Direct Selection marquee across the +/// edge of the group's fill takes the group, and one across the moved member takes it. +#[test] +fn a_marquee_takes_a_groups_own_fill_inside_a_painted_layer() { + let mut s = session(); + let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff"); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null})); + let l = s.doc().unwrap().doc.layers[0].id; + run(&mut s, "appearance.addFill", json!({"ids": [l.0]})); + assert!(!s.doc().unwrap().doc.layers[0].appearance.items.is_empty(), "the layer has a fill of its own"); + assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved"); + let doc = &s.doc().unwrap().doc; + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]); + assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]); +} diff --git a/crates/engine/src/tests/spelling.rs b/crates/engine/src/tests/spelling.rs index dd10df1597..107c8b0418 100644 --- a/crates/engine/src/tests/spelling.rs +++ b/crates/engine/src/tests/spelling.rs @@ -345,6 +345,134 @@ fn misspellings_of_one_object_are_what_the_check_lists() { assert_eq!(found.iter().map(|m| m.range.clone()).collect::>(), [listed[0].clone(), listed[2].clone()]); } +/// The (id, start, word) of each word a check lists, and its `more`. +fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) { + let r = run(s, "text.spelling.check", p); + let words = r["words"] + .as_array() + .unwrap() + .iter() + .map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string())) + .collect(); + (words, r["more"].as_bool().unwrap()) +} + +/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of +/// that type object first, then the objects after it, and nothing listed twice. +#[test] +fn a_check_goes_on_from_where_the_last_one_stopped() { + let mut s = session(); + let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx"); + let b = text(&mut s, 100.0, "zzqqx"); + let (first, more) = listed(&mut s, json!({"max": 2})); + assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true)); + // From the end of the second word: the third, in the next paragraph of the same object, not + // the start of the next object. + let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2})); + assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false)); + // A byte inside a word starts from the next word. + let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}})); + assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string()))); + // `from` follows the ids given, groups' type included. + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1})); + assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true)); + let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1})); + assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false)); + let bad = [ + json!({"from": {"id": a.0}}), + json!({"from": {"id": a.0, "byte": -1}}), + json!({"from": {"id": a.0, "byte": 1000}}), + json!({"from": {"id": a.0, "byte": 0, "x": 1}}), + json!({"from": a.0}), + json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}), + json!({"max": 0}), + json!({"max": 10_001}), + json!({"max": "2"}), + ]; + for p in bad { + assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused"); + } +} + +/// One type object with one unknown word more than a check lists: going on from the last word +/// listed reaches the last one. +#[test] +fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() { + use crate::cmd::spelling::MAX_WORDS; + let mut s = session(); + let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" ")); + let r = run(&mut s, "text.spelling.check", json!({})); + let words = r["words"].as_array().unwrap(); + assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true))); + let end = words.last().unwrap()["end"].as_u64().unwrap(); + let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}})); + assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false)); +} + +/// The plain text of type object `id`. +fn plain(s: &Session, id: NodeId) -> String { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not type"), + } +} + +/// Change All's command replaces every word listed, in several objects, as one undo step, and +/// refuses a list with any word not in its object's text, changing nothing. +#[test] +fn change_all_replaces_every_word_listed_in_one_undo_step() { + let mut s = session(); + let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw"); + let b = text(&mut s, 100.0, "é qzxvw"); + let depth = s.doc().unwrap().history.undo.len(); + let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]); + let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words})); + assert_eq!(r["changed"], 4); + assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string())); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string())); + let bad = [ + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}), + json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}), + json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}), + json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}), + json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}), + json!({"to": "x", "words": {"id": a.0}}), + json!({"words": []}), + ]; + for p in bad { + assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused"); + } + assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list"); + assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0); +} + +/// A listed word that already reads as `to` is left alone: with no other word, no edit and no +/// undo step, so the redo history stays. +#[test] +fn change_all_skips_words_that_already_read_as_the_replacement() { + let mut s = session(); + let a = text(&mut s, 50.0, "fixed qzxvw"); + run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"})); + run(&mut s, "edit.undo", json!({})); + let (undo, redo) = { + let h = &s.doc().unwrap().history; + (h.undo.len(), h.redo.len()) + }; + let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]})); + assert_eq!(r["changed"], 0); + let h = &s.doc().unwrap().history; + assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept"); + let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]); + assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1); + assert_eq!(plain(&s, a), "fixed fixed"); +} + /// Each change to the custom dictionary moves its generation on, whether it is saved or not, so /// what Auto Spell Check found before is checked again. #[test] diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index e59e9a90b1..2d29d98a23 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -262,8 +262,8 @@ fn document_color_mode_converts_effect_colors() { assert_eq!((object(&s), style(&s)), before); } -/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn -/// again after the switch paints its series and labels in the new mode. +/// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a +/// graph drawn again after the switch paints its series, labels and lines in the new mode. #[test] fn document_color_mode_converts_the_paints_a_graph_keeps() { let mut s = session(); @@ -284,22 +284,26 @@ fn document_color_mode_converts_the_paints_a_graph_keeps() { } // A fill row on the label, which the graph keeps with the label's rows. run(&mut s, "appearance.addFill", json!({"ids": [label.0]})); + // A stroke on an axis line, which the graph keeps for its axis lines and tick marks. + let line = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })).unwrap().id; + run(&mut s, "paint.setStroke", json!({"color": "#ff0000", "ids": [line.0]})); let kept = |s: &Session| -> Vec { let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone(); let rows = [&g.label_styles.values_rows, &g.label_styles.categories_rows, &g.label_styles.legend_rows]; let rows: Vec = rows.into_iter().flatten().filter_map(|r| r.paint.fill.as_ref()?.color()).collect(); + let lines = g.label_styles.axis_rows.iter().filter_map(|r| r.paint.stroke.as_ref()?.color()); let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend]; let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap()); - g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).collect() + g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).chain(lines).collect() }; let before = kept(&s); - assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 3]); + assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 4]); let undo = s.doc().unwrap().history.undo.len(); run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); let cmyk = first_fill(doc(&s).node(red).unwrap()); assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); - assert_eq!(kept(&s), [cmyk; 3]); + assert_eq!(kept(&s), [cmyk; 4]); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); // Drawn again from new data, the series keeps the converted color. run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]})); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 62587f4824..ed4a82dce6 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -4027,3 +4027,35 @@ fn apply_fill_to_stroke_with_characters_selected_changes_only_them() { let labels = undo_labels(&s); assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke"))); } + +/// Redefines `[Normal Character Style]` with `fill` (`charStyle.setAttrs`). +fn set_normal_fill(s: &mut Session, fill: vectorcraft_color::Paint) { + let attrs = crate::cmd::textstyles::char_attrs(&CharStyle { fill, ..CharStyle::default() }); + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}})).unwrap(); +} + +/// #7975: type the Type tool starts is filled as [Normal Character Style] is, black unless it was +/// redefined, not with the current fill a shape left behind. +#[test] +fn new_type_takes_the_normal_character_style_fill_not_the_current_fill() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let v = ViewInfo::default(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "the current fill is red"); + s.select_tool("type", v).unwrap(); + click(&mut s, 200.0, 200.0); + s.tool_text("Black", v).unwrap(); + let id = s.doc().unwrap().selection.objects[0]; + assert_eq!(obj(&s, id).runs[0].style.fill, Paint::solid(Color::BLACK)); + // A redefined [Normal Character Style] gives new type its fill. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + set_normal_fill(&mut s, blue.clone()); + let made = s.execute("text.create", &json!({"x": 100, "y": 300, "text": "Blue"})).unwrap(); + assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, blue); + // A color given to the command still wins. + let made = s.execute("text.create", &json!({"x": 100, "y": 400, "text": "Green", "color": "#00ff00"})).unwrap(); + assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, Paint::solid(Color::rgb(0.0, 1.0, 0.0))); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 1134f6963a..9250cf8030 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1347,6 +1347,18 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { + use vectorcraft_tools::cropimage as crop; + // The most the selected image can be cropped to, when one is selected. + let max = self.doc().ok().and_then(|st| { + let (id, _) = crop::selected_image(&st.doc, &st.selection)?; + match &st.doc.node(id)?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1), + _ => None, + } + }); + crop::check_options(&values, max)?; + } // The Place queue is read later, by a click outside any automation scope: its files must // be readable now, under the roots of whoever sets it. if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) { diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 30d0dc96cf..b661478e0f 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -963,6 +963,13 @@ fn structured_junk() { ("addon.pathtools.trim", json!({"points": [[0, 0], [1e7, 1e7], [-1e7, 5], [0, 0]]})), ("addon.pathtools.trim", json!({"points": [[0, 0], [1, "y"], null]})), ("addon.pathtools.trim", json!({"at": [50, 50], "tolerance": 100})), + // Path Precision Tools: Tangent Circle. + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3], "radius": 1e6, "circle": u64::MAX})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3, 4], "radius": f64::MIN_POSITIVE, "circle": -1})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 2], "radius": "1 mm"})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3], "radius": 0.01, "circle": 64})), + ("addon.pathtools.tangentCircle", json!({"ids": [2, 3, 4]})), + ("addon.pathtools.tangentCircle", json!({"ids": "x", "radius": f64::NAN, "circle": 1.5})), // Arrange Tools add-on. ("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})), ("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})), diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index fb5903c411..40752a2fce 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -579,6 +579,29 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { assert!(failures.is_empty(), "{failures:#?}"); } +/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two +/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its +/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by +/// no more than 4, and no alpha is off. +#[test] +fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() { + let lights = json!([ + {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, + {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} + ]); + let (mut s, _) = setup("threeD.inflate"); + let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}}); + s.execute("effect.setParams", &change).unwrap(); + s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap(); + let image = render(doc(&s)); + let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); + assert!(measured > 2_000, "{measured} pixels inside"); + assert!( + holes == 0 && color <= 1 && max <= 4, + "of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" + ); +} + /// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at /// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the /// live art. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 598e66bc3d..ffa6397805 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -12338,8 +12338,8 @@ fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() { } /// A clipping path inside art cut to a clipping object is written as its fills and its strokes, -/// two objects: its text wrap options are written once, whether it has both or only strokes, and -/// with its strokes when the region outside leaves nothing of its fills. +/// two objects: its text wrap options are written once, whether it has both, only strokes, or +/// fills the region outside leaves nothing of. #[test] fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { for (fill, left, width) in [(solid(Color::gray(0.5)), 20.0, 2.0), (Paint::None, 20.0, 2.0), (solid(Color::gray(0.5)), 101.0, 4.0)] { @@ -12450,3 +12450,151 @@ fn a_graph_with_art_left_out_is_written_without_records() { assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{max}: {text}"); } } + +/// The wrap shapes [`vectorcraft_doc::text::resolve_wrap`] gives the area type in `doc`. +fn area_wrap(doc: &Document) -> Vec { + let mut d = doc.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut d); + let mut out = vec![]; + d.layers[0].walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) + { + out.clone_from(&t.wrap); + } + }); + out +} + +/// `got` and `want` are the same wrap shapes: the same options, offsets within `1e-6`, and the +/// same subpaths with anchors within `1e-3`. +fn same_shapes(got: &[vectorcraft_doc::WrapShape], want: &[vectorcraft_doc::WrapShape], case: &str) { + let same = got.len() == want.len() + && got.iter().zip(want).all(|(g, w)| { + g.wrap.invert == w.wrap.invert + && (g.wrap.offset - w.wrap.offset).abs() < 1e-6 + && g.path.subpaths.len() == w.path.subpaths.len() + && g.path.subpaths.iter().zip(&w.path.subpaths).all(|(a, b)| { + a.closed == b.closed + && a.anchors.len() == b.anchors.len() + && a.anchors.iter().zip(&b.anchors).all(|(p, q)| (p.p - q.p).hypot() < 1e-3) + }) + }); + assert!(same, "{case}\n{got:?}\n{want:?}"); +} + +/// A clipping object that isn't written as an object of its own (a group, an image, a symbol +/// instance, a path or compound path without paint in art cut to a clipping object) or is written +/// as its outlines or cut (type, a path the outer clipping object cuts) keeps its text wrap options on one unpainted object +/// of its wrap outline: area type below it wraps alike after a round trip, and the object stays +/// locked or hidden as it was. A clipping object without options gets no such object. +#[test] +fn a_clipping_object_not_written_whole_keeps_its_text_wrap() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let cases = ["group", "hidden", "locked", "image", "instance", "type", "unpainted path", "unpainted compound", "cut path", "no options"]; + for case in cases { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + area.runs = vec![TextRun::new("One two three four five six", st)]; + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 200.0)) }; + area.xf = Affine::IDENTITY; + let area = text_node(&mut doc, area); + doc.insert(Some(layer), usize::MAX, area).unwrap(); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let mut cutter = match case { + "group" | "hidden" | "locked" | "no options" => { + let mut off = square(&mut doc, Rect::new(200.0, 20.0, 230.0, 60.0), Color::gray(0.5)); + off.visible = false; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + off, + ]; + group(&mut doc, members, false) + } + "image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None), + "instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))), + "type" => { + let label = TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK)); + text_node(&mut doc, label) + } + "unpainted path" => clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0))), + "unpainted compound" => { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default()); + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }) + } + _ => { + let mut c = clipping(&mut doc, shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 80.0))); + c.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + c + } + }; + cutter.visible = case != "hidden"; + cutter.locked = case == "locked"; + let cutter = if case == "no options" { cutter } else { wrapped(cutter, -4.5, true) }; + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let mut top = group(&mut doc, vec![cutter, member], true); + if matches!(case, "unpainted path" | "unpainted compound" | "cut path") { + let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9)); + let frame = group(&mut doc, vec![frame], false); + top = group(&mut doc, vec![frame, top], true); + } + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let text = program(&doc); + let back = read_back(&doc); + if case == "no options" { + assert!(!text.contains("(AI11TextWrapOffset)"), "{text}"); + assert!(wraps(back.layers[0].children().unwrap()).is_empty()); + continue; + } + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{case}\n{text}"); + same_wraps(&wraps(back.layers[0].children().unwrap()), &[(None, -4.5, true)]); + let mut carrier = None; + back.layers[0].walk(&mut |n| { + if n.extras().wrap.is_some() { + carrier = Some((n.locked, n.visible)); + } + }); + assert_eq!(carrier, Some((case == "locked", case != "hidden")), "{case}"); + let want = area_wrap(&doc); + assert_eq!(want.is_empty(), case == "hidden", "{case}"); + same_shapes(&area_wrap(&back), &want, case); + } +} + +/// With too little room for the unpainted object that carries a clipping object's text wrap +/// options, the options are left out, never written on another object, and the data stays readable. +#[test] +fn a_clipping_objects_text_wrap_is_left_out_without_room() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + ]; + let cutter = wrapped(group(&mut doc, members, false), 2.0, false); + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let top = group(&mut doc, vec![cutter, member], true); + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for room in 0..=all { + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(crate::import::objects_read(&out.program).unwrap() <= room); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + // The group, then the compound path of the two squares (three objects): with room for all four + // the options are written, on that compound path. + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), usize::from(room >= 4), "{room}\n{text}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let mut carriers = vec![]; + back.layers[0].walk(&mut |n| { + if n.extras().wrap.is_some() { + carriers.push(matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty()); + } + }); + assert_eq!(carriers, if room >= 4 { vec![true] } else { vec![] }, "{room}\n{text}"); + } +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 7c211add4d..e32118fe5f 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -1232,25 +1232,22 @@ impl<'a> Writer<'a> { /// A container's members, the first one's outline cutting the others: its fills painted /// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text - /// wrap options are written once: with its fills, or with its strokes when no fill object is - /// written (it has no fills, or the region outside leaves nothing of them). + /// wrap options are written once, under them all ([`Self::wrap_carrier`]), and not with its fills + /// or strokes, which may be cut or left out. fn clip_contents(&mut self, children: &[Arc]) { let Some((first, rest)) = children.split_first() else { return }; + self.wrap_carrier(first); // Nothing to clip by hides the clipped art. let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return }; let mut paint = first.clip_paint(); + for part in [&mut paint.fill, &mut paint.stroke].into_iter().flatten() { + part.extras_mut().wrap = None; + } let outer = self.clip.clone(); let region = self.cut(&PathData::from_bezpath(&outline), rule); self.clip = Some(region); if let Some(fill) = &paint.fill { - let objects = self.objects; self.node(fill); - if self.objects > objects - && let Some(stroke) = &mut paint.stroke - && stroke.extras().wrap.is_some() - { - stroke.extras_mut().wrap = None; - } } for c in rest { self.node(c); @@ -1261,6 +1258,28 @@ impl<'a> Writer<'a> { } } + /// The text wrap options of clipping object `first`, when it has them, on an unpainted path + /// (a compound path for several subpaths) of the outline area type wraps around + /// ([`vectorcraft_doc::text::wrap_outline`]), uncut, locked and hidden as `first` is. Nothing is + /// written for an empty outline or without room for the path ([`Self::take_objects`]). + fn wrap_carrier(&mut self, first: &Node) { + let Some(wrap) = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return }; + let outline = vectorcraft_doc::text::wrap_outline(first); + if outline.is_empty() { + return; + } + self.state(first.locked, !first.visible); + let start = self.body.len(); + self.plain_object(&outline, FillRule::NonZero, None, None, Xy::of(first).object()); + if self.body.len() == start { + return; + } + self.block_end = usize::MAX; + self.body.push_str("%_/ArtDictionary :\n"); + self.text_wrap(wrap); + self.body.push_str("%_;\n%_\n"); + } + /// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path. fn cut(&self, path: &PathData, rule: FillRule) -> PathData { match &self.clip { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index aa4a4c5c78..7e21bf9fdf 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -310,6 +310,10 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. const KEY_ENTRY_BYTES: usize = 32; +/// The most units of a computed property name an error about a property of `null` or `undefined` +/// names; a longer name is left out of the message. +const NAMED_KEY_UNITS: usize = 256; + #[cfg(test)] thread_local! { /// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at. @@ -1077,8 +1081,8 @@ impl Interp { } fn not_defined(&mut self, name: &[u16]) -> Abrupt { - let message = format!("{} is not defined", String::from_utf16_lossy(name)); - self.throw(ErrorType::Reference, &message) + let ident = String::from_utf16_lossy(name); + self.throw(ErrorType::Reference, &format!("{ident} is not defined")) } fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> { @@ -1332,12 +1336,9 @@ impl Interp { Value::Number(_) => Ok(self.intrinsics.number_proto), Value::Bool(_) => Ok(self.intrinsics.boolean_proto), Value::Undefined | Value::Null => { - let message = format!( - "cannot read property '{}' of {}", - String::from_utf16_lossy(k), - if matches!(v, Value::Null) { "null" } else { "undefined" } - ); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(k); + let base = if matches!(v, Value::Null) { "null" } else { "undefined" }; + Err(self.type_error(&format!("cannot read property '{key}' of {base}"))) } } } @@ -1434,8 +1435,8 @@ impl Interp { fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { - let message = format!("cannot define property '{}': {why}", String::from_utf16_lossy(k)); - return Err(self.type_error(&message)); + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot define property '{key}': {why}"))); } Ok(false) } @@ -1588,8 +1589,8 @@ impl Interp { fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { if throw { - let message = format!("cannot assign to property '{}': {why}", String::from_utf16_lossy(k)); - return Err(self.type_error(&message)); + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot assign to property '{key}': {why}"))); } Ok(()) } @@ -1684,8 +1685,8 @@ impl Interp { Ok(true) } Some(_) if throw => { - let message = format!("cannot delete property '{}'", String::from_utf16_lossy(k)); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(k); + Err(self.type_error(&format!("cannot delete property '{key}'"))) } Some(_) => Ok(false), } @@ -1703,12 +1704,9 @@ impl Interp { self.put(*o, k, v, throw) } Value::Undefined | Value::Null => { - let message = format!( - "cannot set property '{}' of {}", - String::from_utf16_lossy(&k), - if matches!(base, Value::Null) { "null" } else { "undefined" } - ); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(&k); + let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; + Err(self.type_error(&format!("cannot set property '{key}' of {base}"))) } _ => { let proto = self.primitive_proto(base, &k)?; @@ -1742,16 +1740,30 @@ impl Interp { self.replace(2, v) } - fn check_coercible(&mut self, base: &Value, k: &[u16]) -> JsResult<()> { - if base.is_nullish() { - self.primitive_proto(base, k)?; + /// Throws when `base` is `null` or `undefined`, naming the property `k` when it is a primitive + /// of at most [`NAMED_KEY_UNITS`] units, which converts without running script code, and the + /// access as a read, or as a write when `set`. + fn check_coercible(&mut self, base: &Value, k: Option<&Value>, set: bool) -> JsResult<()> { + if !base.is_nullish() { + return Ok(()); } - Ok(()) + let key = match k { + Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None, + Some(Value::Object(_)) | None => None, + Some(k) => Some(self.to_str(k)?.to_rust_string()), + }; + let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; + Err(match (key, set) { + (Some(key), false) => self.type_error(&format!("cannot read property '{key}' of {base}")), + (Some(key), true) => self.type_error(&format!("cannot set property '{key}' of {base}")), + (None, false) => self.type_error(&format!("cannot read a property of {base}")), + (None, true) => self.type_error(&format!("cannot set a property of {base}")), + }) } fn op_check_object(&mut self) -> JsResult<()> { let base = self.peek(0)?; - self.check_coercible(&base, &[]) + self.check_coercible(&base, None, true) } fn op_to_key(&mut self) -> JsResult<()> { @@ -1760,7 +1772,7 @@ impl Interp { if self.is_xml_access(&base, &k) { return Ok(()); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), true)?; let name = self.to_key(&k)?; self.replace(1, Value::String(Str::from_rc(name))) } @@ -1778,7 +1790,7 @@ impl Interp { let v = self.xml_get(&base, &k)?; return self.replace(2, v); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?; self.replace(2, v)?; if with_this { self.push(base) } else { Ok(()) } @@ -1817,7 +1829,7 @@ impl Interp { let r = self.xml_delete(&base, &k)?; return self.replace(2, Value::Bool(r)); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let name = self.to_key(&k)?; let o = self.to_object(&base)?; let strict = self.strict(); @@ -1850,7 +1862,7 @@ impl Interp { self.xml_put(&base, &k, &Value::Number(new))?; return self.replace(2, Value::Number(if prefix { new } else { old })); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?; self.replace(2, r) } @@ -2573,8 +2585,8 @@ impl Interp { self.put(object, name.clone(), v, true) } Some(_) => { - let message = format!("cannot declare function {}", String::from_utf16_lossy(name)); - Err(self.type_error(&message)) + let ident = String::from_utf16_lossy(name); + Err(self.type_error(&format!("cannot declare function {ident}"))) } } } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 93c487b378..9f9c59a96f 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -239,6 +239,27 @@ fn errors_carry_line_and_column() { assert_eq!(e.message, "42"); } +/// An error about a property of `null` or `undefined` names a computed property whose name is a +/// primitive, and says whether the script read or set it, never naming an empty property; a +/// member assignment, an object key and a long name leave the name out. +#[test] +fn errors_about_null_and_undefined_name_the_property() { + for (source, message) in [ + ("null[1]", "TypeError: cannot read property '1' of null"), + ("var u; u['k'] += 1", "TypeError: cannot set property 'k' of undefined"), + ("var u; u['k']++", "TypeError: cannot read property 'k' of undefined"), + ("delete null[true]", "TypeError: cannot read property 'true' of null"), + ("var u; u['k'] = 1", "TypeError: cannot set property 'k' of undefined"), + ("null.x", "TypeError: cannot read property 'x' of null"), + ("var u; u.y = 1", "TypeError: cannot set a property of undefined"), + ("var u; u[{}] = 1", "TypeError: cannot set a property of undefined"), + ("null[new Array(300).join('a')]", "TypeError: cannot read a property of null"), + ] { + assert_eq!(fail(source).message, message, "{source}"); + } + truth("var k = {toString: function () { throw 1; }}; try { null[k]; false } catch (e) { e instanceof TypeError }"); +} + #[test] fn host_functions_receive_arguments_and_return_values() { let mut realm = Realm::new(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 3066e8e835..b3db2cfc88 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -854,7 +854,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index a20a4a5b36..516cfe6235 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,7 +4,8 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]) and the Parametric Shape Tool's shapes ([`shapes`]). +//! ([`divide_dashes`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch +//! two or three shapes ([`tangent_circles`]). mod crossings; mod dashes; @@ -12,6 +13,7 @@ mod extend; pub mod shapes; mod shared_edge; mod slide; +mod tangent_circle; #[cfg(test)] mod tests; mod trim; @@ -28,6 +30,7 @@ pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at}; +pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLES, TangentCircleError, tangent_circle_segments, tangent_circles}; pub use trim::{Span, slice, span_at, spans, without_spans}; use crate::fit::{end_tangent, start_tangent}; diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index c20e559d96..bcc254aa82 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -226,6 +226,27 @@ impl Default for Work { } } +impl Work { + /// One `n`th of the work of [`Work::default`] (all of it for `n` of 0 or 1). + pub const fn share(n: usize) -> Work { + let n = if n == 0 { 1 } else { n }; + Work { pairs: MAX_PAIRS / n, steps: MAX_STEPS / n } + } + + /// The work done since the budget was `before`. + pub fn spent_since(self, before: Work) -> Work { + Work { pairs: before.pairs.saturating_sub(self.pairs), steps: before.steps.saturating_sub(self.steps) } + } + + /// Take `cost` (from [`Work::spent_since`]) out of what is left, as if that work were done + /// again. `None`, leaving the budget as it was, when less than `cost` is left. + pub fn draw(&mut self, cost: Work) -> Option<()> { + let (pairs, steps) = (self.pairs.checked_sub(cost.pairs)?, self.steps.checked_sub(cost.steps)?); + *self = Work { pairs, steps }; + Some(()) + } +} + /// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself /// included): the places on `path`, in order, within the work of [`Work::default`]. pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option> { diff --git a/crates/pathops/src/addons/pathtools/tangent_circle.rs b/crates/pathops/src/addons/pathtools/tangent_circle.rs new file mode 100644 index 0000000000..b17a52cac6 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangent_circle.rs @@ -0,0 +1,744 @@ +//! Tangent Circle: the circles that touch two shapes and have a given radius, or that touch three +//! shapes. A circle touches a shape when it meets the shape's outline without crossing it: the +//! whole outline lies outside the circle (its nearest point is on the circle) or inside it (its +//! farthest point is on the circle). At a smooth point of the outline the circle is tangent there; +//! at a corner or an open end it passes through that point. +//! +//! When every shape is a four-segment Bézier circle the answer is closed-form (the problem of +//! Apollonius for three), then moved onto the drawn outlines. +//! Otherwise the centers are isolated on a grid that is split where a root can be: the distance +//! from a point to an outline changes by at most the distance the point moves, so a cell whose +//! center is too far from every condition holds no center and is dropped. The cells left are +//! refined with Newton's method on the exact curves. + +use kurbo::{CubicBez, ParamCurve, Point, Vec2}; +use vectorcraft_geom::PathData; + +#[cfg(test)] +mod tests; + +/// Most segments the shapes may hold together, counted by [`tangent_circle_segments`]. +pub const MAX_TANGENT_CIRCLE_SEGMENTS: usize = 2_000; + +/// The segments of `p`'s subpaths, a lone anchor counting as one. +pub fn tangent_circle_segments(p: &PathData) -> usize { + p.subpaths.iter().map(|sp| sp.segment_count().max(usize::from(!sp.anchors.is_empty()))).sum() +} +/// Most circles one call returns. +pub const MAX_TANGENT_CIRCLES: usize = 64; +/// With three shapes, the largest radius looked for, as a multiple of the diagonal of the box +/// around the shapes' anchors and handles. +const MAX_RADIUS_FACTOR: f64 = 64.0; + +/// A circle by its center and radius. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Circle { + pub center: Point, + pub radius: f64, +} + +/// Why [`tangent_circles`] gives no answer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TangentCircleError { + /// Not two shapes with a radius above 0, nor three shapes without one; or a shape with no + /// outline, or values that are not finite. + BadInput, + /// More than [`MAX_TANGENT_CIRCLE_SEGMENTS`] segments, or a search that would take too long. + TooComplex, + /// More than [`MAX_TANGENT_CIRCLES`] circles: the shapes may be touched along a whole curve + /// (two concentric circles, for example). + TooMany, +} + +/// The circles that touch every one of `shapes` (document coordinates): two shapes and `radius`, +/// or three shapes and no radius. They are listed by radius, then top to bottom, then left to +/// right; an empty list when no circle touches them all. +pub fn tangent_circles(shapes: &[&PathData], radius: Option) -> Result, TangentCircleError> { + use TangentCircleError::*; + match (shapes.len(), radius) { + (2, Some(r)) if r.is_finite() && r > 0.0 => {} + (3, None) => {} + _ => return Err(BadInput), + } + if shapes.iter().map(|p| tangent_circle_segments(p)).sum::() > MAX_TANGENT_CIRCLE_SEGMENTS { + return Err(TooComplex); + } + let mut bounds = None::; + // The smallest shape's diagonal. + let mut smallest = f64::INFINITY; + for p in shapes { + if p.subpaths.iter().all(|sp| sp.anchors.is_empty()) { + return Err(BadInput); + } + let b = p.control_bounds().ok_or(BadInput)?; + smallest = smallest.min(b.width().hypot(b.height())); + bounds = Some(bounds.map_or(b, |a| a.union(b))); + } + let bounds = bounds.ok_or(BadInput)?; + let finite = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()); + // The work is done about the bounds' center and in units of their diagonal. + let origin = bounds.center(); + let scale = bounds.width().hypot(bounds.height()); + if !finite || !scale.is_finite() || scale <= 0.0 { + return Err(BadInput); + } + let local = |p: Point| Point::new((p.x - origin.x) / scale, (p.y - origin.y) / scale); + let r = radius.map(|r| r / scale); + if r.is_some_and(|r| !r.is_finite()) { + // Shapes so small that the radius is past any number in their units. + return Err(BadInput); + } + let circles: Option> = + shapes.iter().map(|p| as_circle(p).map(|c| Circle { center: local(c.center), radius: c.radius / scale })).collect(); + // Two of three shapes the same circle up to rounding, or two copies of the same path: every + // circle touching it and the third touches all three. + let same = |a: &Circle, b: &Circle| (a.center - b.center).hypot() <= COPY && (a.radius - b.radius).abs() <= COPY; + if shapes.len() == 3 + && (0..3).any(|i| match &circles { + Some(c) => same(&c[i], &c[(i + 1) % 3]), + None => shapes[i] == shapes[(i + 1) % 3], + }) + { + return Err(TooMany); + } + let outlines: Vec = shapes.iter().map(|p| Outline::new(p, &local)).collect(); + let found = match circles { + Some(c) => { + let exact = match r { + Some(r) => two_circles(c[0], c[1], r)?, + None => apollonius(c[0], c[1], c[2]).into_iter().filter(|c| c.radius <= MAX_RADIUS_FACTOR).collect(), + }; + // The paths are Bézier circles: each answer is polished on their outlines. + exact.into_iter().map(|found| on_outlines(&outlines, &c, r, found)).collect() + } + None => numeric(&outlines, r)?, + }; + // Answers about a shape far smaller than the gaps between the shapes can be closer together than + // `SAME`: the tolerance shrinks with that shape. + let tolerance = SAME.min(smallest / scale * 1e-3).max(COPY); + let mut out = dedup(found, tolerance); + if out.len() > MAX_TANGENT_CIRCLES { + return Err(TooMany); + } + sort(&mut out, tolerance); + Ok(out + .into_iter() + .map(|c| Circle { center: Point::new(origin.x + c.center.x * scale, origin.y + c.center.y * scale), radius: c.radius * scale }) + .filter(|c| c.center.x.is_finite() && c.center.y.is_finite() && c.radius.is_finite()) + .collect()) +} + +/// `found`, an answer for the ideal circles `ideal`, moved by Newton's method to touch the +/// `outlines` of the paths themselves in the same way: each circle's outline lies outside the answer +/// (nearest point), or inside it when the answer holds that circle (farthest point). `found` as it +/// is when the method does not settle nearby: where the answer is within the Bézier circles' own +/// error (0.0273% of the radius) of touching them in two places or none, it follows the true +/// circles. +fn on_outlines(outlines: &[Outline], ideal: &[Circle], r: Option, found: Circle) -> Circle { + let mut combo = 0; + for (i, c) in ideal.iter().enumerate() { + let d = (found.center - c.center).hypot(); + let holds = (d + c.radius - found.radius).abs(); + if holds < (d - c.radius - found.radius).abs() && holds < (c.radius - d - found.radius).abs() { + combo |= 1 << i; + } + } + newton(outlines, r, combo, found.center, 1e-4, &mut 0.0) + .filter(|c| (c.center - found.center).hypot() <= 1e-3 && (c.radius - found.radius).abs() <= 1e-3) + .unwrap_or(found) +} + +/// `path` as a circle when it is a four-segment Bézier circle: one closed subpath of four curved +/// segments with a square bounding box, lying within 0.03% of the radius of a circle (its largest +/// error is 0.0273%). +fn as_circle(path: &PathData) -> Option { + let [sp] = path.subpaths.as_slice() else { return None }; + if !sp.closed || sp.segment_count() != 4 || (0..4).any(|i| sp.segment_is_line(i)) { + return None; + } + let b = path.bounds()?; + let radius = (b.width() + b.height()) / 4.0; + if !radius.is_finite() || radius <= 0.0 || (b.width() - b.height()).abs() > 1e-6 * radius { + return None; + } + let center = b.center(); + let near = |p: Point| ((p - center).hypot() - radius).abs() <= 3e-4 * radius; + let round = (0..sp.segment_count()).all(|i| { + let seg = sp.segment(i); + (0..=16).all(|k| near(seg.eval(k as f64 / 16.0))) + }); + round.then_some(Circle { center, radius }) +} + +/// Below this (in units of the bounds' diagonal) two values are the same. +const EPS: f64 = 1e-9; + +/// The circles of radius `r` touching circles `a` and `b`: their centers are `a.radius + r` from +/// `a`'s center (outside it) or `|a.radius - r|` (inside it, or holding it), and the same for `b`. +/// A distance of 0 (`r` equal to that circle's radius) puts the center on that circle's center. +/// Concentric circles at a distance both allow touch along a whole circle: [`TangentCircleError::TooMany`]. +fn two_circles(a: Circle, b: Circle, r: f64) -> Result, TangentCircleError> { + let mut out = vec![]; + let apart = (a.center - b.center).hypot(); + let only = |ok: bool, p: Point| if ok { vec![p] } else { vec![] }; + for da in [a.radius + r, (a.radius - r).abs()] { + for db in [b.radius + r, (b.radius - r).abs()] { + let centers = match (da <= EPS, db <= EPS) { + (true, true) => only(apart <= EPS, a.center), + (true, false) => only((apart - db).abs() <= EPS, a.center), + (false, true) => only((apart - da).abs() <= EPS, b.center), + (false, false) if apart <= EPS && (da - db).abs() <= EPS => return Err(TangentCircleError::TooMany), + (false, false) => circle_crossings(a.center, da, b.center, db), + }; + out.extend(centers.into_iter().map(|center| Circle { center, radius: r })); + } + } + Ok(out) +} + +/// Where the circle about `c1` of radius `r1` meets the one about `c2` of radius `r2`: none, one +/// where they touch, or two. +fn circle_crossings(c1: Point, r1: f64, c2: Point, r2: f64) -> Vec { + let v = c2 - c1; + let d = v.hypot(); + if d <= EPS || d > r1 + r2 + EPS || d < (r1 - r2).abs() - EPS { + return vec![]; + } + let along = (d * d + r1 * r1 - r2 * r2) / (2.0 * d); + let h2 = r1 * r1 - along * along; + let u = v / d; + let foot = c1 + u * along; + // Only rounding takes a touching pair below 0; two crossings closer than `SAME` become one later. + if h2 <= 0.0 { + return vec![foot]; + } + let n = Vec2::new(-u.y, u.x) * h2.sqrt(); + vec![foot + n, foot - n] +} + +/// The circles touching circles `c` (the problem of Apollonius): for each choice of outside (+) +/// or inside (−) per circle, `|center − cᵢ|² = (r ± rᵢ)²`. Subtracting the first equation from the +/// others leaves two linear equations in x, y and r; two of the three unknowns follow from the +/// third, and the first equation gives a quadratic in it. +fn apollonius(a: Circle, b: Circle, c: Circle) -> Vec { + let cs = [a, b, c]; + let mut out = vec![]; + for signs in 0..8u8 { + let s = [0, 1, 2].map(|i| if signs & (1 << i) == 0 { 1.0 } else { -1.0 }); + let (x1, y1, r1) = (cs[0].center.x, cs[0].center.y, cs[0].radius * s[0]); + let row = |i: usize| { + let (x, y, ri) = (cs[i].center.x, cs[i].center.y, cs[i].radius * s[i]); + ([2.0 * (x - x1), 2.0 * (y - y1), 2.0 * (ri - r1)], (x * x + y * y - ri * ri) - (x1 * x1 + y1 * y1 - r1 * r1)) + }; + let (m1, b1) = row(1); + let (m2, b2) = row(2); + // Keep the third unknown free whose 2×2 minor is largest. + let minor = |i: usize, j: usize| m1[i] * m2[j] - m1[j] * m2[i]; + let Some((free, (i, j))) = + [(2, (0, 1)), (1, (0, 2)), (0, (1, 2))].into_iter().max_by(|p, q| minor(p.1.0, p.1.1).abs().total_cmp(&minor(q.1.0, q.1.1).abs())) + else { + continue; + }; + let det = minor(i, j); + if det.abs() <= EPS { + continue; + } + // vᵢ = αᵢ + βᵢ t, vⱼ = αⱼ + βⱼ t, with t the free unknown. + let alpha_i = (b1 * m2[j] - b2 * m1[j]) / det; + let beta_i = (-m1[free] * m2[j] + m2[free] * m1[j]) / det; + let alpha_j = (m1[i] * b2 - m2[i] * b1) / det; + let beta_j = (-m1[i] * m2[free] + m2[i] * m1[free]) / det; + let unknowns = |t: f64| { + let mut v = [0.0; 3]; + v[free] = t; + v[i] = alpha_i + beta_i * t; + v[j] = alpha_j + beta_j * t; + v + }; + // (x − x1)² + (y − y1)² − (r + r1)² as a quadratic in t. + let [v0, v1] = [unknowns(0.0), unknowns(1.0)]; + let lin = [v0[0] - x1, v0[1] - y1, v0[2] + r1]; + let dir = [v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]]; + let qa = dir[0] * dir[0] + dir[1] * dir[1] - dir[2] * dir[2]; + let qb = 2.0 * (lin[0] * dir[0] + lin[1] * dir[1] - lin[2] * dir[2]); + let qc = lin[0] * lin[0] + lin[1] * lin[1] - lin[2] * lin[2]; + for t in quadratic_roots(qa, qb, qc) { + let [x, y, r] = unknowns(t); + if r > EPS && [x, y, r].iter().all(|v| v.is_finite()) { + out.push(Circle { center: Point::new(x, y), radius: r }); + } + } + } + out +} + +/// The real roots of `a t² + b t + c`, a double root once; none when every coefficient is 0. +fn quadratic_roots(a: f64, b: f64, c: f64) -> Vec { + let size = a.abs().max(b.abs()).max(c.abs()); + if size == 0.0 { + return vec![]; + } + let (a, b, c) = (a / size, b / size, c / size); + if a.abs() <= EPS { + return if b.abs() <= EPS { vec![] } else { vec![-c / b] }; + } + let disc = b * b - 4.0 * a * c; + if disc < -1e-12 { + return vec![]; + } + if disc <= 1e-12 { + return vec![-b / (2.0 * a)]; + } + // The root that adds magnitudes first; with b = 0 either sign does. + let q = if b < 0.0 { -0.5 * (b - disc.sqrt()) } else { -0.5 * (b + disc.sqrt()) }; + vec![q / a, c / q] +} + +/// Circles closer than this (in units of the bounds' diagonal) are one. +const SAME: f64 = 1e-6; +/// Given circles closer than this (in units of the bounds' diagonal) are copies of one circle. +const COPY: f64 = 1e-12; + +/// Sorts `circles` (local units) by radius, then top to bottom, then left to right. Values within +/// `tolerance` of each other (the radii of mirror images, for example) sort as equal. +fn sort(circles: &mut [Circle], tolerance: f64) { + let key = |v: f64| (v / tolerance).round(); + circles.sort_by(|a, b| { + key(a.radius).total_cmp(&key(b.radius)).then(key(a.center.y).total_cmp(&key(b.center.y))).then(key(a.center.x).total_cmp(&key(b.center.x))) + }); +} + +/// `found` with each circle within `tolerance` of an earlier one left out. +fn dedup(found: Vec, tolerance: f64) -> Vec { + let mut out: Vec = vec![]; + for c in found { + if !out.iter().any(|o| (o.center - c.center).hypot() <= tolerance && (o.radius - c.radius).abs() <= tolerance) { + out.push(c); + } + } + out +} + +/// A shape's outline, in local units: its segments, and chords that lie within `slack` of them. +struct Outline { + segments: Vec, + /// Each segment's neighbors along its subpath (before, after), where it has them. + beside: Vec<(Option, Option)>, + /// (start, end, segment, t at start, t at end). + chords: Vec<(Point, Point, usize, f64, f64)>, + /// The farthest the chords are from the segments. + slack: f64, +} + +/// How far chords may stray from their segment, at most (local units); each segment is cut into +/// at most [`MAX_CHORDS`] chords, so a tightly bent one may stray more. +const CHORD_SLACK: f64 = 1e-3; +const MAX_CHORDS: usize = 64; + +impl Outline { + fn new(path: &PathData, local: &dyn Fn(Point) -> Point) -> Self { + let mut o = Outline { segments: vec![], beside: vec![], chords: vec![], slack: 0.0 }; + for sp in &path.subpaths { + let n = sp.segment_count(); + if n == 0 { + if let Some(a) = sp.anchors.first() { + // A lone anchor: a segment that stays on its point. + let p = local(a.p); + o.segments.push(CubicBez::new(p, p, p, p)); + o.beside.push((None, None)); + o.chords.push((p, p, o.segments.len() - 1, 0.0, 1.0)); + } + continue; + } + let first = o.segments.len(); + for i in 0..n { + let s = sp.segment(i); + let seg = CubicBez::new(local(s.p0), local(s.p1), local(s.p2), local(s.p3)); + let k = o.segments.len(); + let before = if i > 0 { Some(k - 1) } else { sp.closed.then_some(first + n - 1) }; + let after = if i + 1 < n { Some(k + 1) } else { sp.closed.then_some(first) }; + // |B''| is at most 6 × the larger second difference; a chord over a parameter step + // h strays at most |B''| h² / 8. + let bend = 6.0 + * (seg.p0.to_vec2() - 2.0 * seg.p1.to_vec2() + seg.p2.to_vec2()) + .hypot() + .max((seg.p1.to_vec2() - 2.0 * seg.p2.to_vec2() + seg.p3.to_vec2()).hypot()); + let pieces = ((bend / (8.0 * CHORD_SLACK)).sqrt().ceil() as usize).clamp(1, MAX_CHORDS); + o.slack = o.slack.max(bend / (8.0 * (pieces * pieces) as f64)); + let mut prev = seg.p0; + for j in 1..=pieces { + let t = j as f64 / pieces as f64; + let p = if j == pieces { seg.p3 } else { seg.eval(t) }; + o.chords.push((prev, p, k, (j - 1) as f64 / pieces as f64, t)); + prev = p; + } + o.segments.push(seg); + o.beside.push((before, after)); + } + } + o + } + + /// The chords' nearest and farthest distance from `q`. + fn reach(&self, q: Point) -> Reach { + let mut r = Reach { near: f64::INFINITY, far: -1.0 }; + for &(a, b, ..) in &self.chords { + r.near = r.near.min(chord_near(q, a, b).0); + r.far = r.far.max((q - a).hypot()).max((q - b).hypot()); + } + r + } + + /// The point of the curves nearest `q` (or farthest, `far`) and its distance. Every segment + /// whose chords come within twice the slack of the chords' best answer may hold the true one, + /// so each is polished from its own best chord point, and the best result is kept. + fn extreme(&self, q: Point, far: bool) -> (Point, f64) { + let better = |a: f64, b: f64| if far { a > b } else { a < b }; + let worst = if far { -1.0 } else { f64::INFINITY }; + // Each segment's best chord distance and the parameter where it is reached. + let mut per = vec![(worst, 0.0); self.segments.len()]; + for &(a, b, seg, t0, t1) in &self.chords { + let (d, u) = if far { + let (da, db) = ((q - a).hypot(), (q - b).hypot()); + if db > da { (db, 1.0) } else { (da, 0.0) } + } else { + chord_near(q, a, b) + }; + if let Some(slot) = per.get_mut(seg) + && better(d, slot.0) + { + *slot = (d, t0 + (t1 - t0) * u); + } + } + let best = per.iter().fold(worst, |m, p| if better(p.0, m) { p.0 } else { m }); + let window = 2.0 * self.slack + 1e-12; + let mut out: Option<(Point, f64)> = None; + for (seg, &(d, t)) in per.iter().enumerate() { + if (d - best).abs() > window { + continue; + } + let mut tries = vec![(seg, t)]; + let (before, after) = self.beside.get(seg).copied().unwrap_or((None, None)); + if t <= 0.0 + && let Some(b) = before + { + tries.push((b, 1.0)); + } + if t >= 1.0 + && let Some(a) = after + { + tries.push((a, 0.0)); + } + for (s, t) in tries { + let Some(curve) = self.segments.get(s) else { continue }; + let (p, d) = polish(*curve, q, t, far); + if out.is_none_or(|(_, od)| better(d, od)) { + out = Some((p, d)); + } + } + } + out.unwrap_or((q, 0.0)) + } +} + +/// The distance from `q` to the chord from `a` to `b`, and the parameter along it where it is reached. +fn chord_near(q: Point, a: Point, b: Point) -> (f64, f64) { + let ab = b - a; + let len2 = ab.hypot2(); + let u = if len2 > 0.0 { ((q - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + ((q - (a + ab * u)).hypot(), u) +} + +struct Reach { + near: f64, + far: f64, +} + +/// The nearest (or farthest) point to `q` on `seg` near parameter `t`: Newton's method on +/// (B(t) − q)·B′(t) = 0, kept in 0..1, keeping only steps that improve the distance. +fn polish(seg: CubicBez, q: Point, t: f64, far: bool) -> (Point, f64) { + let dist = |t: f64| (seg.eval(t) - q).hypot(); + let better = |a: f64, b: f64| if far { a > b } else { a < b }; + let (mut t, mut d) = (t, dist(t)); + let [p0, p1, p2, p3] = [seg.p0, seg.p1, seg.p2, seg.p3].map(Point::to_vec2); + for _ in 0..16 { + let mt = 1.0 - t; + let d1 = 3.0 * (mt * mt * (p1 - p0) + 2.0 * mt * t * (p2 - p1) + t * t * (p3 - p2)); + let d2 = 6.0 * (mt * (p2 - 2.0 * p1 + p0) + t * (p3 - 2.0 * p2 + p1)); + let w = seg.eval(t) - q; + let f = w.dot(d1); + let df = d1.hypot2() + w.dot(d2); + if df == 0.0 || !df.is_finite() { + break; + } + let next = (t - f / df).clamp(0.0, 1.0); + let nd = dist(next); + if !better(nd, d) && nd != d { + break; + } + let moved = (next - t).abs(); + (t, d) = (next, nd); + if moved < 1e-15 { + break; + } + } + (seg.eval(t), d) +} + +/// Most grid cells the search looks at, over all levels. +const MAX_CELLS: usize = 400_000; +/// Most cells × chords the search may measure. +const MAX_WORK: f64 = 1.5e8; +/// Most cells Newton's method starts from. +const MAX_TRIES: usize = 4_000; +/// Most chords Newton's method may measure, over all its starts. +const MAX_NEWTON_WORK: f64 = 1.5e8; + +/// Which of a shape's two distances a condition uses: the nearest point (the outline outside the +/// circle) or the farthest (the outline inside it). +fn far_of(combo: usize, shape: usize) -> bool { + combo & (1 << shape) != 0 +} + +/// The circles touching `outlines` (local units): two outlines and radius `r`, or three and none. +fn numeric(outlines: &[Outline], r: Option) -> Result, TangentCircleError> { + let n = outlines.len(); + let combos = 1usize << n; + let slack = outlines.iter().map(|o| o.slack).fold(0.0, f64::max); + let chords: usize = outlines.iter().map(|o| o.chords.len()).sum(); + let reach = match r { + Some(r) => r, + None => MAX_RADIUS_FACTOR, + }; + // A center is within the radius of a point of every outline, so within its bounds grown by it. + let mut area: Option = None; + let mut whole: Option = None; + for o in outlines { + let b = o.chords.iter().fold(None::, |b, &(p, q, ..)| { + let c = kurbo::Rect::from_points(p, q); + Some(b.map_or(c, |b| b.union(c))) + }); + let Some(b) = b else { return Err(TangentCircleError::BadInput) }; + whole = Some(whole.map_or(b, |w| w.union(b))); + let b = b.inflate(reach + slack, reach + slack); + area = Some(area.map_or(b, |a| a.intersect(b))); + } + let whole = whole.ok_or(TangentCircleError::BadInput)?.inflate(slack, slack); + let span = whole.width().hypot(whole.height()); + let Some(area) = area.filter(|a| a.width() >= 0.0 && a.height() >= 0.0) else { return Ok(vec![]) }; + let side = area.width().max(area.height()).max(1e-12); + let leaf = 2.0 * slack.max(1e-4); + let mut half = side / 2.0; + // The cells alive at the current level: (center, combos still possible). + let all = (1u32 << combos) - 1; + let mut cells = vec![(area.center(), all)]; + let mut looked = 0usize; + let test = |c: Point, half: f64, alive: u32| -> u32 { + let corner = half * std::f64::consts::SQRT_2; + let e = corner + slack; + // Seen from far off, the directions to any two points of the outlines differ little, and + // so do the gradients of their distances: the difference of two distances changes by at + // most 2 × span / (distance to the outlines) per unit moved, rather than 2. + let off = { + let dx = (whole.x0 - c.x).max(c.x - whole.x1).max(0.0); + let dy = (whole.y0 - c.y).max(c.y - whole.y1).max(0.0); + dx.hypot(dy) - corner + }; + let steep = if off > 0.0 { (2.0 * span / off).min(2.0) } else { 2.0 }; + let apart = steep * corner + 2.0 * slack; + let reach: Vec = outlines.iter().map(|o| o.reach(c)).collect(); + let d = |i: usize, combo: usize| if far_of(combo, i) { reach[i].far } else { reach[i].near }; + let mut keep = 0; + for combo in 0..combos { + if alive & (1 << combo) == 0 { + continue; + } + let ok = match r { + Some(r) => (0..n).all(|i| (d(i, combo) - r).abs() <= e), + None => { + let (d0, d1, d2) = (d(0, combo), d(1, combo), d(2, combo)); + (d0 - d1).abs() <= apart && (d0 - d2).abs() <= apart && (d1 - d2).abs() <= apart && d0 - e <= MAX_RADIUS_FACTOR + } + }; + if ok { + keep |= 1 << combo; + } + } + keep + }; + loop { + looked += cells.len(); + if looked > MAX_CELLS || looked as f64 * chords as f64 > MAX_WORK { + return Err(TangentCircleError::TooComplex); + } + cells = cells.into_iter().filter_map(|(c, alive)| Some((c, test(c, half, alive))).filter(|x| x.1 != 0)).collect(); + if half * std::f64::consts::SQRT_2 <= leaf || cells.is_empty() { + break; + } + let q = half / 2.0; + cells = cells + .into_iter() + .flat_map(|(c, alive)| [(-q, -q), (q, -q), (-q, q), (q, q)].map(|(dx, dy)| (Point::new(c.x + dx, c.y + dy), alive))) + .collect(); + half = q; + } + // The leaf cells of each combination, in clusters of touching cells. Newton's method starts + // from up to [`SEEDS`] cells of each cluster, each the farthest from those before it. A cluster + // around one center (or two that nearly meet) gives one or two circles; three or more far apart + // mean the shapes are touched along a whole curve. + let step = 2.0 * half; + let mut out = vec![]; + let mut tries = 0usize; + let mut work = 0.0; + let same = |a: &Circle, b: &Circle| (a.center - b.center).hypot() <= SAME && (a.radius - b.radius).abs() <= SAME; + let mut solve = |seed: Point, combo: usize| -> Result, TangentCircleError> { + tries += 1; + let c = newton(outlines, r, combo, seed, half, &mut work); + if tries > MAX_TRIES || work > MAX_NEWTON_WORK { + return Err(TangentCircleError::TooComplex); + } + Ok(c) + }; + for combo in 0..combos { + let leaves: Vec = cells.iter().filter(|(_, a)| a & (1 << combo) != 0).map(|(c, _)| *c).collect(); + let mut found: Vec = vec![]; + for cluster in clusters(&leaves, step) { + let mut seeds: Vec = vec![]; + let mut here: Vec = vec![]; + while seeds.len() < SEEDS { + let next = cluster + .iter() + .copied() + .map(|c| (c, seeds.iter().map(|s| (*s - c).hypot()).fold(f64::INFINITY, f64::min))) + .max_by(|a, b| a.1.total_cmp(&b.1)); + let Some((seed, gap)) = next else { break }; + if !seeds.is_empty() && gap <= 2.0 * step { + break; + } + seeds.push(seed); + if let Some(c) = solve(seed, combo)? + && !here.iter().any(|o| same(o, &c)) + { + here.push(c); + } + } + if here.len() > 2 { + return Err(TangentCircleError::TooMany); + } + for c in here { + if !found.iter().any(|o| same(o, &c)) { + found.push(c); + } + } + if found.len() > MAX_TANGENT_CIRCLES { + return Err(TangentCircleError::TooMany); + } + } + out.extend(found); + } + Ok(out) +} + +/// Seeds Newton's method starts from in one cluster of cells, at most. +const SEEDS: usize = 4; + +/// `cells`, centers on a grid `step` apart, in groups of cells that touch (sides or corners). +fn clusters(cells: &[Point], step: f64) -> Vec> { + use std::collections::HashMap; + let Some(first) = cells.first() else { return vec![] }; + let key = |p: &Point| (((p.x - first.x) / step).round() as i64, ((p.y - first.y) / step).round() as i64); + let mut at: HashMap<(i64, i64), usize> = cells.iter().enumerate().map(|(i, p)| (key(p), i)).collect(); + let mut out = vec![]; + for p in cells { + let Some(start) = at.remove(&key(p)) else { continue }; + let mut group = vec![]; + let mut stack = vec![start]; + while let Some(i) = stack.pop() { + let Some(c) = cells.get(i) else { continue }; + group.push(*c); + let (kx, ky) = key(c); + for dx in -1..=1 { + for dy in -1..=1 { + if let Some(j) = at.remove(&(kx + dx, ky + dy)) { + stack.push(j); + } + } + } + } + out.push(group); + } + out +} + +/// Newton's method from `seed` on the conditions of `combo`: with `r`, distance(i) = r for both +/// outlines; without, the three distances equal (the radius). Adds the chords it measures to `work`. +fn newton(outlines: &[Outline], r: Option, combo: usize, seed: Point, step: f64, work: &mut f64) -> Option { + let mut c = seed; + let n = outlines.len(); + let cost: f64 = outlines.iter().map(|o| o.chords.len() as f64).sum(); + let limit = (step * 8.0).max(1e-3); + // A radius the search sets itself (three shapes) is kept within its limit. + let fits = |radius: f64| radius > EPS && (r.is_some() || radius <= MAX_RADIUS_FACTOR); + for _ in 0..60 { + *work += cost; + let mut d = [0.0; 3]; + let mut u = [Vec2::ZERO; 3]; + for i in 0..n { + let (p, di) = outlines[i].extreme(c, far_of(combo, i)); + if di <= EPS { + return None; + } + d[i] = di; + u[i] = (c - p) / di; + } + let (f, rows, radius) = match r { + Some(r) => ([d[0] - r, d[1] - r], [u[0], u[1]], r), + None => ([d[0] - d[1], d[0] - d[2]], [u[0] - u[1], u[0] - u[2]], d[0]), + }; + if f[0].abs().max(f[1].abs()) <= 1e-12 { + return fits(radius).then_some(Circle { center: c, radius }); + } + let det = rows[0].cross(rows[1]); + let mut delta = if det.abs() > 1e-9 { + // J Δ = −f, with J's rows the gradients. + Vec2::new(-(f[0] * rows[1].y - f[1] * rows[0].y) / det, -(rows[0].x * f[1] - rows[1].x * f[0]) / det) + } else { + // Rows (nearly) parallel: the least-squares step (JᵀJ + λI) Δ = −Jᵀf, which still + // closes the residual along the rows' direction. + let g = rows[0] * f[0] + rows[1] * f[1]; + let lambda = 1e-12; + let (a, b, d) = ( + rows[0].x * rows[0].x + rows[1].x * rows[1].x + lambda, + rows[0].x * rows[0].y + rows[1].x * rows[1].y, + rows[0].y * rows[0].y + rows[1].y * rows[1].y + lambda, + ); + let m = a * d - b * b; + if !m.is_finite() || m == 0.0 { + break; + } + Vec2::new(-(d * g.x - b * g.y) / m, -(a * g.y - b * g.x) / m) + }; + let len = delta.hypot(); + if !len.is_finite() { + return None; + } + if len > limit { + delta *= limit / len; + } + c += delta; + if delta.hypot() <= 1e-15 { + break; + } + } + // Stopped short of 1e-12: keep it only when it is close (a double root converges slowly). + *work += cost; + let mut d = [0.0; 3]; + for i in 0..n { + d[i] = outlines[i].extreme(c, far_of(combo, i)).1; + } + let (worst, radius) = match r { + Some(r) => ((d[0] - r).abs().max((d[1] - r).abs()), r), + None => ((d[0] - d[1]).abs().max((d[0] - d[2]).abs()), d[0]), + }; + (worst <= 1e-8 && fits(radius)).then_some(Circle { center: c, radius }) +} diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs new file mode 100644 index 0000000000..8b63d29873 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs @@ -0,0 +1,487 @@ +use kurbo::{Affine, Point, Rect}; +use vectorcraft_geom::{PathData, SubPath, shapes}; + +use super::*; + +fn circle(x: f64, y: f64, r: f64) -> PathData { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)) +} + +fn square(x: f64, y: f64, half: f64) -> PathData { + shapes::rectangle(Rect::new(x - half, y - half, x + half, y + half)) +} + +/// Is `c` touching the ideal circle about `center` of radius `r`: `|c − center| = c.r ± r`? +fn touches_circle(c: &Circle, center: Point, r: f64, tol: f64) -> bool { + let d = (c.center - center).hypot(); + (d - (c.radius + r)).abs() <= tol || (d - (c.radius - r).abs()).abs() <= tol +} + +/// The nearest and farthest distance from `q` to points `pts`, a dense sampling of a curve. +fn reach(pts: &[Point], q: Point) -> (f64, f64) { + pts.iter().fold((f64::INFINITY, 0.0), |(lo, hi), p| { + let d = (*p - q).hypot(); + (lo.min(d), hi.max(d)) + }) +} + +/// Does circle `c` touch the densely sampled outline `pts`: its nearest or farthest point on the circle? +fn touches(c: &Circle, pts: &[Point], tol: f64) -> bool { + let (lo, hi) = reach(pts, c.center); + (lo - c.radius).abs() <= tol || (hi - c.radius).abs() <= tol +} + +/// Points along every segment of `path`, `n` per segment. +fn samples(path: &PathData, n: usize) -> Vec { + path.subpaths + .iter() + .flat_map(|sp| (0..sp.segment_count()).flat_map(move |i| (0..n).map(move |k| sp.segment(i).eval(k as f64 / n as f64)))) + .collect() +} + +fn has(found: &[Circle], center: Point, r: f64, tol: f64) -> bool { + found.iter().any(|c| (c.center - center).hypot() <= tol && (c.radius - r).abs() <= tol) +} + +#[test] +fn three_circles_give_the_eight_apollonius_circles() { + // Equal circles about the corners of a 3-4-5 triangle: the circumcenter (2, 1.5) at 2.5 from + // each center gives the circle outside all three (r = 2.5 − 1) and the one holding all three + // (r = 2.5 + 1). + let shapes = [circle(0.0, 0.0, 1.0), circle(4.0, 0.0, 1.0), circle(0.0, 3.0, 1.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + // The answers are polished on the Bézier circles, which stray up to 0.0273% of their radius + // from the ideal ones. + let tol = 2e-3; + assert_eq!(found.len(), 8, "{found:?}"); + assert!(has(&found, Point::new(2.0, 1.5), 1.5, tol), "{found:?}"); + assert!(has(&found, Point::new(2.0, 1.5), 3.5, tol), "{found:?}"); + for c in &found { + for (center, r) in [(Point::new(0.0, 0.0), 1.0), (Point::new(4.0, 0.0), 1.0), (Point::new(0.0, 3.0), 1.0)] { + assert!(touches_circle(c, center, r, tol), "{c:?} and {center:?}"); + } + } + // Listed by radius. + assert!(found.windows(2).all(|w| w[0].radius <= w[1].radius + 1e-9)); +} + +#[test] +fn answers_for_circles_touch_the_drawn_bezier_outlines() { + // Radius-100 Bézier circles stray up to 0.027 pt from the ideal circles; the answers touch the + // drawn outlines far closer than that. + let shapes = [circle(0.0, 0.0, 100.0), circle(500.0, 40.0, 100.0), circle(180.0, 420.0, 100.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + let dense: Vec> = shapes.iter().map(|s| samples(s, 20_000)).collect(); + for c in &found { + for pts in &dense { + assert!(touches(c, pts, 1e-3), "{c:?}"); + } + } + let pair = tangent_circles(&[&shapes[0], &shapes[1]], Some(250.0)).unwrap(); + assert!(!pair.is_empty()); + for c in &pair { + assert!(touches(c, &dense[0], 1e-3) && touches(c, &dense[1], 1e-3), "{c:?}"); + } +} + +#[test] +fn three_circles_of_different_sizes() { + // A worked case: circles (0,0) r 1, (10,0) r 2, (5,8) r 3. Every answer satisfies the + // tangency equations, and there are eight since no circle holds or crosses another. + let defs = [(0.0, 0.0, 1.0), (10.0, 0.0, 2.0), (5.0, 8.0, 3.0)]; + let shapes = defs.map(|(x, y, r)| circle(x, y, r)); + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + for c in &found { + for (x, y, r) in defs { + assert!(touches_circle(c, Point::new(x, y), r, 5e-3), "{c:?}"); + } + } +} + +#[test] +fn only_true_circles_take_the_closed_form() { + assert!(as_circle(&circle(0.0, 0.0, 100.0)).is_some()); + // Turned, a Bézier circle keeps its square box. + assert!(as_circle(&circle(0.0, 0.0, 100.0).transformed(Affine::rotate(0.35))).is_some()); + // A 200 × 200.1 ellipse is searched along its own outline. + assert!(as_circle(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.1))).is_none()); + assert!(as_circle(&square(0.0, 0.0, 10.0)).is_none()); + // A 720-sided polygon lies within 0.03% of its circle, but is searched as drawn. + let polygon: Vec = (0..720) + .map(|k| Point::new(100.0 * (k as f64 / 360.0 * std::f64::consts::PI).cos(), 100.0 * (k as f64 / 360.0 * std::f64::consts::PI).sin())) + .collect(); + assert!(as_circle(&PathData::single(SubPath::polyline(&polygon, true))).is_none()); +} + +#[test] +fn quadratics_without_a_linear_term_give_both_roots() { + let mut roots = quadratic_roots(1.0, 0.0, -1.0); + roots.sort_by(f64::total_cmp); + assert_eq!(roots, vec![-1.0, 1.0]); + let mut roots = quadratic_roots(2.0, -0.0, -8.0); + roots.sort_by(f64::total_cmp); + assert_eq!(roots, vec![-2.0, 2.0]); +} + +#[test] +fn three_circles_keep_the_radius_limit() { + // Nearly in a row: some answers have radii near 1250, past 64 × the bounds' diagonal (about 770). + let shapes = [circle(0.0, 0.0, 1.0), circle(10.0, 0.0, 1.0), circle(5.0, 0.01, 1.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + let b = shapes.iter().map(|s| s.control_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let limit = MAX_RADIUS_FACTOR * b.width().hypot(b.height()); + assert!(!found.is_empty() && found.len() < 8, "{found:?}"); + assert!(found.iter().all(|c| c.radius <= limit), "{found:?}"); +} + +#[test] +fn two_circles_and_a_radius() { + let a = circle(0.0, 0.0, 10.0); + let b = circle(30.0, 0.0, 10.0); + // Polished on the Bézier circles (see above). + let tol = 0.02; + // Radius 5: only the circle in the gap, touching both at once. + let found = tangent_circles(&[&a, &b], Some(5.0)).unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(has(&found, Point::new(15.0, 0.0), 5.0, tol)); + // Radius 20: two outside both, two holding the first and two holding the second. + let found = tangent_circles(&[&a, &b], Some(20.0)).unwrap(); + assert_eq!(found.len(), 6, "{found:?}"); + let h = (30.0f64 * 30.0 - 15.0 * 15.0).sqrt(); + assert!(has(&found, Point::new(15.0, -h), 20.0, tol) && has(&found, Point::new(15.0, h), 20.0, tol)); + for c in &found { + assert!(touches_circle(c, Point::new(0.0, 0.0), 10.0, tol) && touches_circle(c, Point::new(30.0, 0.0), 10.0, tol)); + } + // Top to bottom for one radius. + assert!(found.windows(2).all(|w| w[0].center.y <= w[1].center.y + 1e-9)); + // Radius 10, the circles' own, 20 apart: each circle itself touches the other at one point; with + // the two outside both, four in all. + let c = circle(20.0, 0.0, 10.0); + let found = tangent_circles(&[&a, &c], Some(10.0)).unwrap(); + assert_eq!(found.len(), 4, "{found:?}"); + assert!(has(&found, Point::new(0.0, 0.0), 10.0, tol) && has(&found, Point::new(20.0, 0.0), 10.0, tol), "{found:?}"); + for f in &found { + assert!(touches_circle(f, Point::new(0.0, 0.0), 10.0, tol) && touches_circle(f, Point::new(20.0, 0.0), 10.0, tol), "{f:?}"); + } + // Too small to reach across: none. + let far = circle(100.0, 0.0, 10.0); + assert_eq!(tangent_circles(&[&a, &far], Some(5.0)).unwrap(), vec![]); +} + +#[test] +fn the_numeric_search_agrees_with_the_closed_form() { + // The grid search and Newton on the Bézier outlines find what the closed form finds, within + // the Bézier circle's own error (0.03% of the radius). + let defs = [(0.0, 0.0, 10.0), (35.0, 5.0, 6.0), (12.0, 30.0, 4.0)]; + let shapes = defs.map(|(x, y, r)| circle(x, y, r)); + let refs = [&shapes[0], &shapes[1], &shapes[2]]; + let closed = tangent_circles(&refs, None).unwrap(); + let b = shapes.iter().map(|s| s.control_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let (o, s) = (b.center(), b.width().hypot(b.height())); + let local = |p: Point| Point::new((p.x - o.x) / s, (p.y - o.y) / s); + let outlines: Vec = refs.iter().map(|p| Outline::new(p, &local)).collect(); + let numeric3 = dedup(numeric(&outlines, None).unwrap(), SAME); + assert_eq!(numeric3.len(), closed.len(), "{numeric3:?} vs {closed:?}"); + for c in &closed { + let tol = 1e-3 * c.radius.max(10.0) / s; + assert!(has(&numeric3, local(c.center), c.radius / s, tol), "{c:?} missing from {numeric3:?}"); + } + let closed2 = tangent_circles(&refs[..2], Some(12.0)).unwrap(); + let numeric2 = dedup(numeric(&outlines[..2], Some(12.0 / s)).unwrap(), SAME); + assert_eq!(numeric2.len(), closed2.len(), "{numeric2:?} vs {closed2:?}"); + for c in &closed2 { + assert!(has(&numeric2, local(c.center), c.radius / s, 1e-2 / s), "{c:?}"); + } +} + +/// An ellipse with semi-axes `a` and `b` about the origin, mapped by `m`: its Bézier path and its +/// exact points by angle. +fn mapped_ellipse(a: f64, b: f64, m: Affine) -> (PathData, impl Fn(f64) -> Point + Copy) { + let path = shapes::ellipse(Rect::new(-a, -b, a, b)).transformed(m); + let exact = move |th: f64| m * Point::new(a * th.cos(), b * th.sin()); + (path, exact) +} + +/// Independently of the code under test: the centers of the circles of radius `r` that touch the +/// exact convex curve `exact` (about `middle`) and the circle about `cc` of radius `rc`, in every +/// combination. A center lies on the curve's normal at `r` (outward or inward) where its distance to +/// `cc` is `rc + r` or `|rc − r|`; it counts when the curve's nearest or farthest point from it is +/// at `r`. +fn independent_centers(exact: impl Fn(f64) -> Point + Copy, middle: Point, cc: Point, rc: f64, r: f64) -> Vec { + let tau = std::f64::consts::TAU; + let dense: Vec = (0..100_000).map(|k| exact(k as f64 / 100_000.0 * tau)).collect(); + let n = 200_000; + let mut out: Vec = vec![]; + for side in [1.0, -1.0] { + let normal = move |th: f64| { + let p = exact(th); + let t = (exact(th + 1e-7) - exact(th - 1e-7)).normalize(); + let mut nrm = Vec2::new(t.y, -t.x); + if nrm.dot(p - middle) < 0.0 { + nrm = -nrm; + } + p + nrm * (side * r) + }; + for target in [rc + r, (rc - r).abs()] { + let g = |th: f64| (normal(th) - cc).hypot() - target; + for k in 0..n { + let (mut a, mut b) = (k as f64 / n as f64 * tau, (k + 1) as f64 / n as f64 * tau); + if g(a) * g(b) < 0.0 { + for _ in 0..60 { + let m = (a + b) / 2.0; + if g(a) * g(m) <= 0.0 { b = m } else { a = m } + } + let q = normal(a); + let (lo, hi) = reach(&dense, q); + let touching = (lo - r).abs() <= 1e-3 || (hi - r).abs() <= 1e-3; + if touching && !out.iter().any(|o| (*o - q).hypot() <= 1e-6) { + out.push(q); + } + } + } + } + } + out +} + +/// `found` and `independent` are the same centers, within `tol`. +fn same_centers(found: &[Circle], independent: &[Point], tol: f64) { + assert_eq!(found.len(), independent.len(), "{found:?} vs {independent:?}"); + for p in independent { + assert!(found.iter().any(|c| (c.center - *p).hypot() <= tol), "{p:?} missing from {found:?}"); + } +} + +#[test] +fn a_rotated_ellipse_and_a_circle_match_an_independent_solve() { + let (ellipse, exact) = mapped_ellipse(40.0, 20.0, Affine::rotate(30f64.to_radians())); + let (cc, rc, r) = (Point::new(70.0, 10.0), 12.0, 15.0); + let disc = circle(cc.x, cc.y, rc); + let found = tangent_circles(&[&ellipse, &disc], Some(r)).unwrap(); + // Every circle touches the analytic ellipse and the circle (Bézier error: 0.03% of 40 pt). + let dense: Vec = (0..200_000).map(|k| exact(k as f64 / 200_000.0 * std::f64::consts::TAU)).collect(); + for c in &found { + assert!(touches(c, &dense, 0.03), "{c:?}"); + assert!(touches_circle(c, cc, rc, 0.01), "{c:?}"); + } + // Every combination (outside both, holding the circle, holding the ellipse, inside it) solved + // independently: the same circles. + same_centers(&found, &independent_centers(exact, Point::ZERO, cc, rc, r), 0.05); + // A circle overlapping the ellipse, with a radius large enough to hold either. + let (cc, rc, r) = (Point::new(30.0, 5.0), 15.0, 50.0); + let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap(); + same_centers(&found, &independent_centers(exact, Point::ZERO, cc, rc, r), 0.05); +} + +#[test] +fn a_rotated_and_skewed_ellipse_matches_an_independent_solve() { + let m = Affine::translate((-20.0, 15.0)) * Affine::skew(0.4, 0.0) * Affine::rotate(-0.7); + let (ellipse, exact) = mapped_ellipse(30.0, 12.0, m); + let (cc, rc, r) = (Point::new(15.0, 30.0), 8.0, 20.0); + let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap(); + let independent = independent_centers(exact, m * Point::ZERO, cc, rc, r); + assert!(!independent.is_empty()); + same_centers(&found, &independent, 0.05); +} + +#[test] +fn two_centers_close_together_are_both_found() { + // An ellipse 20 × 10 about (100, 0) and a circle of radius 10 about the origin: a circle of + // radius 35 fits the 70 pt gap between them on the axis. At 35.000003 two circles touch both + // from outside, about 0.011 pt above and below the axis. + let (ellipse, exact) = mapped_ellipse(20.0, 10.0, Affine::translate((100.0, 0.0))); + let (cc, rc, r) = (Point::ZERO, 10.0, 35.000003); + let found = tangent_circles(&[&ellipse, &circle(cc.x, cc.y, rc)], Some(r)).unwrap(); + let independent = independent_centers(exact, Point::new(100.0, 0.0), cc, rc, r); + assert_eq!(independent.iter().filter(|p| (p.x - 45.0).abs() < 1.0).count(), 2, "{independent:?}"); + same_centers(&found, &independent, 0.005); + // Two tiny circles a million points apart, and a radius just past half the gap: the two + // answers are about 22.36 pt above and below the axis, close together in units of the gap. + let (a, b) = (circle(0.0, 0.0, 0.01), circle(1e6, 0.0, 0.01)); + let found = tangent_circles(&[&a, &b], Some(499999.9905)).unwrap(); + assert_eq!(found.len(), 2, "{found:?}"); + for c in &found { + assert!((c.center.x - 5e5).abs() < 0.1 && (c.center.y.abs() - 500f64.sqrt()).abs() < 0.1, "{found:?}"); + } +} + +#[test] +fn three_circles_give_eight_distinct_circles_in_a_steady_order() { + // Mirror-image pairs about y = 0 have radii equal up to rounding: the upper one comes first. + let defs = [(0.0, -5.0, 1.0), (0.0, 5.0, 1.0), (12.0, 0.0, 2.0)]; + let shapes = defs.map(|(x, y, r)| circle(x, y, r)); + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + for (i, a) in found.iter().enumerate() { + for b in &found[i + 1..] { + assert!((a.center - b.center).hypot() + (a.radius - b.radius).abs() > 1e-3, "{a:?} twice in {found:?}"); + } + } + for w in found.windows(2) { + if (w[0].radius - w[1].radius).abs() <= 1e-9 { + assert!(w[0].center.y < w[1].center.y, "{found:?}"); + } + } + // The selection mirrored left to right: the same circles mirrored, in the same order. + let flip = Affine::scale_non_uniform(-1.0, 1.0); + let mirrored = shapes.clone().map(|s| s.transformed(flip)); + let again = tangent_circles(&[&mirrored[0], &mirrored[1], &mirrored[2]], None).unwrap(); + assert_eq!(again.len(), found.len()); + for (a, b) in found.iter().zip(&again) { + assert!((flip * a.center - b.center).hypot() <= 1e-6 && (a.radius - b.radius).abs() <= 1e-6, "{found:?} vs {again:?}"); + } +} + +#[test] +fn radii_equal_up_to_rounding_sort_top_to_bottom() { + let lower = Circle { center: Point::new(0.0, 0.2), radius: 0.1 }; + let upper = Circle { center: Point::new(0.0, -0.2), radius: 0.1 + 1e-13 }; + let wider = Circle { center: Point::new(0.0, -0.5), radius: 0.2 }; + let mut v = [wider, lower, upper]; + sort(&mut v, SAME); + assert_eq!(v, [upper, lower, wider]); +} + +#[test] +fn the_nearest_point_is_looked_for_on_every_segment_it_may_be_on() { + // An arc bulging to y = −0.3 whose one chord lies on y = 0, and a line on y = −0.25. Seen from + // (0, −1), the line's chord is nearer (0.75 against 1.0), but the arc itself is (0.7). + let arc = CubicBez::new((-1.0, 0.0), (-1.0, -0.4), (1.0, -0.4), (1.0, 0.0)); + let line = CubicBez::new((-0.5, -0.25), (-0.2, -0.25), (0.2, -0.25), (0.5, -0.25)); + let outline = Outline { + segments: vec![arc, line], + beside: vec![(None, None), (None, None)], + chords: vec![(arc.p0, arc.p3, 0, 0.0, 1.0), (line.p0, line.p3, 1, 0.0, 1.0)], + slack: 0.3, + }; + let (p, d) = outline.extreme(Point::new(0.0, -1.0), false); + assert!((d - 0.7).abs() <= 1e-9 && (p - Point::new(0.0, -0.3)).hypot() <= 1e-9, "{p:?} {d}"); +} + +#[test] +fn copies_among_three_shapes_are_a_whole_family() { + use TangentCircleError::*; + // A circle turned and turned back differs from itself by rounding only. + let b = circle(3.0, 7.0, 20.0); + let turned = b.transformed(Affine::rotate(0.3)).transformed(Affine::rotate(-0.3)); + assert_ne!(b, turned); + assert_eq!(tangent_circles(&[&b, &turned, &circle(100.0, 0.0, 5.0)], None), Err(TooMany)); + // Two copies of a square. + let sq = square(0.0, 0.0, 10.0); + assert_eq!(tangent_circles(&[&sq, &sq.clone(), &square(60.0, 0.0, 10.0)], None), Err(TooMany)); + // Two circles half a point apart, a million points from the third, are not copies. + let far = [circle(0.0, 0.0, 10.0), circle(0.0, 0.5, 10.0), circle(1e6, 0.0, 10.0)]; + assert_ne!(tangent_circles(&[&far[0], &far[1], &far[2]], None), Err(TooMany)); +} + +#[test] +fn three_squares_are_solved_numerically() { + let shapes = [square(0.0, 0.0, 10.0), square(60.0, 0.0, 10.0), square(30.0, 50.0, 10.0)]; + let found = tangent_circles(&[&shapes[0], &shapes[1], &shapes[2]], None).unwrap(); + assert!(!found.is_empty()); + let dense: Vec> = shapes.iter().map(|s| samples(s, 4000)).collect(); + for c in &found { + for pts in &dense { + assert!(touches(c, pts, 0.01), "{c:?}"); + } + } + // By symmetry, the circle in the middle touching all three from outside is centered on x = 30. + let inner = found.iter().find(|c| (c.center.x - 30.0).abs() < 1e-6 && c.center.y > 0.0 && c.center.y < 40.0); + assert!(inner.is_some(), "{found:?}"); +} + +#[test] +fn compound_and_far_off_paths_give_the_same_circles_moved() { + // A ring (two subpaths of one path) and a small square in its hole. + let mut ring = circle(0.0, 0.0, 50.0); + ring.subpaths.extend(circle(0.0, 0.0, 30.0).subpaths); + let dot = square(0.0, 0.0, 5.0); + // Radius 12: in the hole 18 from the center, and 12 from a corner of the square: two by each + // corner. + let found = tangent_circles(&[&ring, &dot], Some(12.0)).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + let (ring_pts, dot_pts) = (samples(&ring, 4000), samples(&dot, 4000)); + for c in &found { + assert!(touches(c, &ring_pts, 0.02) && touches(c, &dot_pts, 0.02), "{c:?}"); + } + // Moved far off and scaled: the same circles, moved and scaled. + let m = Affine::translate((1e6, -2e6)) * Affine::scale(3.0); + let (ring2, dot2) = (ring.transformed(m), dot.transformed(m)); + let moved = tangent_circles(&[&ring2, &dot2], Some(36.0)).unwrap(); + assert_eq!(moved.len(), found.len(), "{moved:?} vs {found:?}"); + for c in &found { + assert!(has(&moved, m * c.center, 3.0 * c.radius, 1e-4), "{c:?}"); + } +} + +#[test] +fn open_paths_and_no_answer() { + let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false)); + let disc = circle(50.0, 40.0, 10.0); + // Radius 10: a center 10 from the line is at least 30 from the disc's center, never 20. + assert_eq!(tangent_circles(&[&line, &disc], Some(10.0)).unwrap(), vec![]); + // Radius 20: centers on y = 20, 30 from (50, 40): x = 50 ± √500. + let found = tangent_circles(&[&line, &disc], Some(20.0)).unwrap(); + assert_eq!(found.len(), 2, "{found:?}"); + let dx = 500f64.sqrt(); + assert!(has(&found, Point::new(50.0 - dx, 20.0), 20.0, 0.05) && has(&found, Point::new(50.0 + dx, 20.0), 20.0, 0.05), "{found:?}"); + // A given radius far past 64 × the bounds' diagonal: two short segments 10 apart and radius + // 1000 (the limit applies only when three shapes set the radius). + let left = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(1.0, 0.0)], false)); + let right = PathData::single(SubPath::polyline(&[Point::new(10.0, 0.0), Point::new(11.0, 0.0)], false)); + let found = tangent_circles(&[&left, &right], Some(1000.0)).unwrap(); + assert!(!found.is_empty()); + let (lp, rp) = (samples(&left, 4000), samples(&right, 4000)); + for c in &found { + assert!(c.radius == 1000.0 && touches(c, &lp, 1e-3) && touches(c, &rp, 1e-3), "{c:?}"); + } + // Two squares far apart with a small radius: none. + let (a, b) = (square(0.0, 0.0, 10.0), square(500.0, 0.0, 10.0)); + assert_eq!(tangent_circles(&[&a, &b], Some(5.0)).unwrap(), vec![]); +} + +#[test] +fn whole_curves_of_answers_and_bad_input_are_errors() { + use TangentCircleError::*; + let (a, b) = (circle(0.0, 0.0, 50.0), circle(0.0, 0.0, 20.0)); + assert_eq!(tangent_circles(&[&a, &b], Some(15.0)), Err(TooMany)); + let (outer, inner) = (square(0.0, 0.0, 50.0), square(0.0, 0.0, 20.0)); + assert_eq!(tangent_circles(&[&outer, &inner], Some(15.0)), Err(TooMany)); + assert_eq!(tangent_circles(&[&a], Some(1.0)), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b], None), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b, &a], Some(1.0)), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b], Some(0.0)), Err(BadInput)); + assert_eq!(tangent_circles(&[&a, &b], Some(f64::NAN)), Err(BadInput)); + // Two of three circles the same: a whole family touches all three. + let third = circle(100.0, 0.0, 5.0); + assert_eq!(tangent_circles(&[&b, &b.clone(), &third], None), Err(TooMany)); + let mut reversed = b.clone(); + reversed.reverse(); + assert_eq!(tangent_circles(&[&b, &reversed, &third], None), Err(TooMany)); + // Shapes so tiny that the radius overflows in their units. + let (tiny_a, tiny_b) = (circle(0.0, 0.0, 1e-305), circle(1e-304, 0.0, 1e-305)); + assert_eq!(tangent_circles(&[&tiny_a, &tiny_b], Some(1e6)), Err(BadInput)); + let empty = PathData::new(vec![]); + assert_eq!(tangent_circles(&[&a, &empty], Some(1.0)), Err(BadInput)); + let big = PathData::single(SubPath::polyline(&(0..2001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect::>(), false)); + assert_eq!(tangent_circles(&[&a, &big], Some(1.0)), Err(TooComplex)); + // Lone anchors count as segments. + let dots = PathData::new((0..2001).map(|i| SubPath::polyline(&[Point::new(i as f64, 0.0)], false)).collect()); + assert_eq!(tangent_circle_segments(&dots), 2001); + assert_eq!(tangent_circles(&[&a, &dots], Some(1.0)), Err(TooComplex)); +} + +#[test] +fn answers_about_a_tiny_shape_far_away_stay_apart() { + // Each tiny circle is touched from outside and from inside: answers 0.02 pt apart on each side, + // eight in all. + let (a, b) = (circle(0.0, 0.0, 0.01), circle(1e6, 0.0, 0.01)); + let found = tangent_circles(&[&a, &b], Some(1e6)).unwrap(); + assert_eq!(found.len(), 8, "{found:?}"); + // All of one radius: top to bottom, then left to right. + for w in found.windows(2) { + let (a, b) = (w[0].center, w[1].center); + assert!(a.y < b.y - 1e-3 || ((a.y - b.y).abs() <= 1e-3 && a.x < b.x), "{found:?}"); + } +} diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs index 301da1a57c..3c6c592d71 100644 --- a/crates/pathops/src/addons/pathtools/tests.rs +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -515,6 +515,29 @@ fn one_work_budget_bounds_several_calls_together() { assert!(crossings_on(&path, &[]).is_some(), "a call of its own has its own budget"); } +#[test] +fn work_done_once_can_be_drawn_again_from_another_budget() { + let row: Vec<(f64, f64)> = (0..=1000).map(|i| (i as f64, 0.0)).collect(); + let path = PathData::single(line(&row, false)); + let start = Work::default(); + let mut work = start; + crossings_on_within(&path, &[], &mut work).unwrap(); + let cost = work.spent_since(start); + // Drawing a call's cost leaves what the call itself leaves, 120 times and no more. + let mut again = Work::default(); + assert_eq!(again.draw(cost), Some(())); + assert_eq!(again, work); + let draws = (1..200).take_while(|_| again.draw(cost).is_some()).count(); + assert_eq!(draws, 119); + let left = again; + assert_eq!(again.draw(cost), None); + assert_eq!(again, left, "a draw that fails takes nothing"); + // A twentieth of the budget pays for the call 6 times. + assert_eq!((Work::share(0), Work::share(1)), (Work::default(), Work::default())); + let mut part = Work::share(20); + assert_eq!((0..200).take_while(|_| part.draw(cost).is_some()).count(), 6); +} + #[test] fn a_segment_that_loops_over_itself_crosses_itself() { // One cubic that meets itself at t = 0.25 and t = 0.75. diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index 635f906839..decff12a65 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -10,6 +10,7 @@ pub mod gif; pub mod jpeg; pub mod png; pub mod psd; +mod psd_type; pub mod quantize; pub mod tga; pub mod tiff; diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 98c031c89a..1dec0423e4 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -7,13 +7,15 @@ use std::sync::Arc; use vectorcraft_color::{BlendMode, cms}; +use vectorcraft_doc::text::TypeAntiAlias; use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind}; -use vectorcraft_geom::Rect; +use vectorcraft_geom::{Point, Rect}; use super::jpeg::{self, ColorModel}; +use super::psd_type; use super::tiff::packbits; use super::{RasterExportOptions, RasterFormat, on_white}; -use crate::{RenderOptions, Rendered, Renderer, fx}; +use crate::{AntiAlias, RenderOptions, Rendered, Renderer, fx}; /// Most pixels a side of a PSD can have (larger images need the format's large-document variant). pub const MAX_SIDE: u32 = 30_000; @@ -33,6 +35,11 @@ pub struct PsdOptions { /// its objects together (a clipping mask, an opacity mask, its own appearance, knockout) stays /// one pixel layer. pub max_editability: bool, + /// With `layers`: horizontal and vertical point type in layers and sublayers is written as type + /// layers that a reader can edit, each with its pixels: type in solid colours without strokes, + /// effects or an appearance of its own. A layer that holds such type becomes a group of its type + /// layers and pixel layers of the art between them. + pub preserve_text: bool, /// With `layers`: hidden layers (and hidden objects) are written as hidden layers instead of /// being left out. pub hidden_layers: bool, @@ -42,7 +49,7 @@ pub struct PsdOptions { impl Default for PsdOptions { fn default() -> Self { - Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, hidden_layers: false, embed_icc: true } + Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, preserve_text: false, hidden_layers: false, embed_icc: true } } } @@ -141,6 +148,8 @@ struct Record { hidden: bool, /// Section divider: [`OPEN_GROUP`] or [`END_GROUP`]. divider: Option, + /// A type layer's type tool object (`TySh`). + type_tool: Option>, } /// Section divider kinds. @@ -159,6 +168,7 @@ impl Record { opacity: 255, hidden: false, divider: None, + type_tool: None, } } @@ -238,6 +248,9 @@ impl Record { if let Some(kind) = self.divider { block(&mut extra, b"lsct", &[&kind.to_be_bytes()[..], b"8BIM", &self.blend].concat())?; } + if let Some(data) = &self.type_tool { + block(&mut extra, b"TySh", data)?; + } out.extend(len32(extra.len())?.to_be_bytes()); out.extend(extra); Ok(()) @@ -451,13 +464,40 @@ impl Parts<'_> { return; } let (hidden, opacity) = (!n.visible, opacity_byte(n.opacity)); - if self.o.max_editability + if self.o.preserve_text + && let Some(t) = psd_type::editable(n) + { + let record = self.draw(n); + let [top, left, bottom, right] = record.rect.map(f64::from); + let origin = Point::new(self.region.x0, self.region.y0); + let aa = if self.ro.anti_alias == AntiAlias::None { TypeAntiAlias::None } else { t.anti_alias }; + let type_tool = Some(psd_type::type_block(t, origin, self.scale, Rect::new(left, top, right, bottom), aa)); + self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, type_tool, ..record }); + return; + } + let per_object = self.o.max_editability; + let hidden_layers = self.o.hidden_layers; + if (per_object || self.o.preserve_text && holds_type(n, hidden_layers)) && splits(n) && let Some(children) = n.children() { self.records.push(Record { divider: Some(END_GROUP), ..Record::empty(GROUP_END.into(), self.colors()) }); - for c in children { - self.add(c); + if per_object { + for c in children { + self.add(c); + } + } else { + // The art between type layers stays together, one pixel layer per stretch. + let mut stretch: Vec> = vec![]; + for c in children { + if type_layer(c, hidden_layers) { + self.add_stretch(n, std::mem::take(&mut stretch)); + self.add(c); + } else { + stretch.push(c.clone()); + } + } + self.add_stretch(n, stretch); } // A group in normal blending lets its layers blend with what is below it. let blend = if n.blend == BlendMode::Normal && !n.isolate { *b"pass" } else { blend_key(n.blend) }; @@ -468,6 +508,22 @@ impl Parts<'_> { self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, ..record }); } + /// `nodes`, children of layer `layer` next to each other, drawn together as one pixel layer + /// named after the layer (nothing when they paint nothing). + fn add_stretch(&mut self, layer: &Node, nodes: Vec>) { + if nodes.is_empty() { + return; + } + let mut part = layer.clone(); + if let Some(children) = part.children_mut() { + *children = nodes; + } + let record = self.draw(&part); + if record.rect != [0; 4] { + self.records.push(record); + } + } + /// `n` drawn alone, visible, at full opacity in normal blending (its record carries those). fn draw(&mut self, n: &Node) -> Record { let name = n.display_name(); @@ -532,6 +588,30 @@ fn splits(n: &Node) -> bool { matches!(n.kind, NodeKind::Layer { clip: false, .. }) && n.extras().mask.is_none() && n.knockout != Knockout::On && !fx::has_object_fx(n) } +/// Does layer `n`, or a sublayer that can be written as a group, hold point type that can be a type +/// layer? Not when other art in it blends in a mode other than normal (the object, or a fill or +/// stroke of it, as [`Node::blends_through`] sees it): drawn as a pixel layer of its own, it would no +/// longer blend with the type or the art below. Hidden type counts only when `hidden` (Include +/// Hidden Layers) writes it. +fn holds_type(n: &Node, hidden: bool) -> bool { + let Some(children) = n.children().filter(|_| splits(n)) else { return false }; + let mut held = false; + for c in children { + if type_layer(c, hidden) { + held = true; + } else if Node::children_blend(std::slice::from_ref(c), &mut |c| c.blends_through()) { + return false; + } + } + held +} + +/// Is child `c` written as a type layer, or as a group holding one ([`holds_type`])? A hidden child +/// is written only when `hidden`. +fn type_layer(c: &Node, hidden: bool) -> bool { + (c.visible || hidden) && (psd_type::editable(c).is_some() || holds_type(c, hidden)) +} + /// Does anything in `n` carry effects of its own that may paint outside the art's bounds? fn reaches_beyond(n: &Node) -> bool { fx::has_object_fx(n) || n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) diff --git a/crates/render/src/encode/psd_type.rs b/crates/render/src/encode/psd_type.rs new file mode 100644 index 0000000000..f65e85bcf9 --- /dev/null +++ b/crates/render/src/encode/psd_type.rs @@ -0,0 +1,547 @@ +//! Type layers of PSD export: point type as a type tool object (the `TySh` block of the format's +//! public specification), so a reader can edit the text. The block holds the text's transform, the +//! text descriptor (the text, its orientation and bounds, and its `EngineData`: the runs of +//! character and paragraph attributes with the fonts they use) and an unwarped warp descriptor. +//! The layer keeps its pixels for readers that show them. + +use vectorcraft_color::Paint; +use vectorcraft_doc::text::TypeAntiAlias; +use vectorcraft_doc::{CharStyle, Composer, Justify, Node, NodeKind, ParaStyle, TextKind, TextObject}; +use vectorcraft_geom::{Affine, Point, Rect}; + +/// Point type that a type layer draws as `n` draws: horizontal or vertical point type with text, +/// whose characters use only the attributes a type layer carries ([`carried`]) in solid colours +/// with whole-number tracking, each drawn with its own font (no fallback font), without strokes or +/// inline graphics, whose paragraphs set only an alignment ([`flat`]) and run left to right, and +/// without System Layout, Optical Margin Alignment, ruby, an appearance of its own, effects or an +/// opacity mask. Other type stays pixels. +pub(super) fn editable(n: &Node) -> Option<&TextObject> { + let NodeKind::Text(t) = &n.kind else { return None }; + let text = t.plain_text(); + let has_cjk = text.chars().any(cjk); + let flat = |p: &ParaStyle| flat(p, has_cjk); + let plain = matches!(t.kind, TextKind::Point) + && !text.is_empty() + && !t.system_layout + && !t.optical_margin + && t.ruby.is_empty() + && !t.stacks_warichu() + && flat(&t.para) + && t.paras.iter().all(flat) + && text.split('\n').enumerate().all(|(i, p)| !vectorcraft_text::paragraph_is_rtl(p, t.para_at(i).direction)) + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && n.extras().mask.is_none() + && !crate::fx::has_object_fx(n) + && t.runs + .iter() + .all(|r| r.inline.is_none() && matches!(r.style.fill, Paint::Solid { .. }) && matches!(r.style.stroke, Paint::None) && carried(&r.style)) + // A type layer's tracking is a whole number of thousandths of an em. + && t.runs.iter().all(|r| r.style.tracking.fract() == 0.0) + // The type layer names one font per run: a character its font lacks would be drawn with + // another. Breaks, joiners and variation selectors draw no glyph of their own (as the + // shaper's `drawn_chars` counts them). + && t.runs.iter().all(|r| face(&r.style).is_some_and(|f| r.text.chars().all(|c| !drawn(c) || f.covers(c)))); + plain.then_some(&**t) +} + +/// Does `c` need a glyph of its own: not a control character (tab, line or paragraph break), a +/// line separator, a joiner or a variation selector? +fn drawn(c: char) -> bool { + !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')) +} + +/// The face the text of style `s` is drawn with: its font version when that is installed. +fn face(s: &CharStyle) -> Option> { + vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref()) +} + +/// Does paragraph `p` set only its alignment, the others being at their defaults (no indents, +/// spacing, tabs, bullets or numbers, direction, Auto Leading, word or letter spacing, glyph scaling +/// or hanging punctuation)? Settings that only choose where area type breaks its lines or what +/// hangs where it breaks them (hyphenation, the single-line or every-line composer, kinsoku, +/// Burasagari, Bunri-Kinshi, breaking Korean anywhere) and the paragraph style's name may be set, +/// and so may Mojikumi when `cjk` is false (it spaces only Chinese, Japanese and Korean characters). +/// A paragraph set to a Standard composer is not flat. +fn flat(p: &ParaStyle, cjk: bool) -> bool { + let only = ParaStyle { + justify: p.justify, + style_name: p.style_name.clone(), + hyphenate: p.hyphenate, + hyphenation: p.hyphenation.clone(), + composer: if matches!(p.composer, Composer::SingleLine | Composer::EveryLine) { p.composer } else { ParaStyle::default().composer }, + kinsoku: p.kinsoku, + kinsoku_type: p.kinsoku_type, + burasagari: p.burasagari, + bunri_kinshi: p.bunri_kinshi, + korean_line_break_anywhere: p.korean_line_break_anywhere, + mojikumi: if cjk { ParaStyle::default().mojikumi } else { p.mojikumi }, + ..ParaStyle::default() + }; + only == *p +} + +/// Is `c` in a block of Chinese, Japanese or Korean characters or their punctuation? +fn cjk(c: char) -> bool { + matches!(c, '\u{1100}'..='\u{11FF}' | '\u{2E80}'..='\u{9FFF}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{F900}'..='\u{FAFF}' | '\u{FE30}'..='\u{FE4F}' | '\u{FF00}'..='\u{FFEF}' | '\u{20000}'..='\u{3FFFF}') +} + +/// Does `s` set only attributes a type layer carries (font and its version, size, leading, +/// tracking, scaling, baseline shift, all caps, underline, strikethrough, fill), the others being +/// at their defaults? Attributes that change nothing drawn without a stroke (the stroke's own +/// settings, overprint, the character style's name) may be set, and so may the language when it +/// is the default, English: USA. The type layer does not record the language, so type in another +/// language stays pixels. +fn carried(s: &CharStyle) -> bool { + if !s.language.as_deref().is_none_or(|l| l.eq_ignore_ascii_case("en-US")) { + return false; + } + let only = CharStyle { + language: s.language.clone(), + font_family: s.font_family.clone(), + font_style: s.font_style.clone(), + font_version: s.font_version.clone(), + size: s.size, + leading: s.leading, + tracking: s.tracking, + baseline_shift: s.baseline_shift, + h_scale: s.h_scale, + v_scale: s.v_scale, + fill: s.fill.clone(), + stroke: s.stroke.clone(), + stroke_width: s.stroke_width, + stroke_cap: s.stroke_cap, + stroke_join: s.stroke_join, + stroke_miter_limit: s.stroke_miter_limit, + stroke_dash: s.stroke_dash.clone(), + stroke_align: s.stroke_align, + overprint_fill: s.overprint_fill, + overprint_stroke: s.overprint_stroke, + style_name: s.style_name.clone(), + underline: s.underline, + strikethrough: s.strikethrough, + all_caps: s.all_caps, + ..CharStyle::default() + }; + only == *s +} + +/// A value of the `EngineData` text engine document. +enum E { + Dict(Vec<(&'static str, E)>), + Array(Vec), + Str(String), + Int(i64), + Real(f64), + Bool(bool), +} + +impl E { + fn is_container(&self) -> bool { + match self { + E::Dict(_) => true, + E::Array(a) => a.iter().any(|v| matches!(v, E::Dict(_) | E::Array(_))), + _ => false, + } + } + + /// Writes the value with tab indents and a key per line. + fn write(&self, depth: usize, out: &mut Vec) { + let tabs = |out: &mut Vec, n: usize| out.extend(std::iter::repeat_n(b'\t', n)); + match self { + E::Dict(items) => { + out.extend(b"<<\n"); + for (k, v) in items { + tabs(out, depth + 1); + out.push(b'/'); + out.extend(k.as_bytes()); + if v.is_container() { + out.push(b'\n'); + tabs(out, depth + 1); + } else { + out.push(b' '); + } + v.write(depth + 1, out); + out.push(b'\n'); + } + tabs(out, depth); + out.extend(b">>"); + } + E::Array(items) if self.is_container() => { + out.extend(b"[\n"); + for v in items { + tabs(out, depth); + v.write(depth, out); + out.push(b'\n'); + } + tabs(out, depth); + out.push(b']'); + } + E::Array(items) => { + out.push(b'['); + for v in items { + out.push(b' '); + v.write(depth, out); + } + out.extend(b" ]"); + } + // UTF-16BE after a byte order mark, with `(`, `)` and `\` escaped. + E::Str(s) => { + out.push(b'('); + for b in [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)) { + if matches!(b, b'(' | b')' | b'\\') { + out.push(b'\\'); + } + out.push(b); + } + out.push(b')'); + } + E::Int(i) => out.extend(i.to_string().as_bytes()), + E::Real(r) => out.extend(real(*r).as_bytes()), + E::Bool(b) => out.extend(if *b { &b"true"[..] } else { b"false" }), + } + } +} + +/// A number as the text engine writes it: `12.0`, `.5`, `-.25`; at most five decimals. +fn real(r: f64) -> String { + if !r.is_finite() { + return "0.0".into(); + } + let mut s = format!("{r:.5}"); + while s.ends_with('0') { + s.pop(); + } + if s.ends_with('.') { + s.push('0'); + } + if s == "-0.0" { + s = "0.0".into(); + } + match (s.strip_prefix("0."), s.strip_prefix("-0.")) { + (Some(rest), _) if rest != "0" => format!(".{rest}"), + (_, Some(rest)) => format!("-.{rest}"), + _ => s, + } +} + +/// A descriptor value (the format's ActionDescriptor items). +enum V { + Text(String), + Enum(&'static str, &'static str), + Long(i32), + Doub(f64), + /// A unit (`#Pnt`: points) and its value. + UntF(&'static [u8; 4], f64), + Objc(&'static str, Vec<(&'static str, V)>), + Raw(Vec), +} + +/// A class, key or enumeration id: a four-character code after a zero length, else its length and +/// bytes. `warp` is written as a string, as readers look it up. +fn id(out: &mut Vec, s: &str) { + if s.len() == 4 && s != "warp" { + out.extend(0u32.to_be_bytes()); + } else { + out.extend((s.len() as u32).to_be_bytes()); + } + out.extend(s.as_bytes()); +} + +/// A Unicode string: its UTF-16 unit count, then the units (`nul`: a terminating zero counted). +fn unicode(out: &mut Vec, s: &str, nul: bool) { + let units: Vec = s.encode_utf16().chain(nul.then_some(0)).collect(); + out.extend((units.len() as u32).to_be_bytes()); + out.extend(units.iter().flat_map(|u| u.to_be_bytes())); +} + +/// A descriptor: an empty class name, the class id, then its items. +fn descriptor(out: &mut Vec, class: &str, items: &[(&str, V)]) { + unicode(out, "", false); + id(out, class); + out.extend((items.len() as u32).to_be_bytes()); + for (key, v) in items { + id(out, key); + match v { + V::Text(s) => { + out.extend(b"TEXT"); + unicode(out, s, true); + } + V::Enum(ty, value) => { + out.extend(b"enum"); + id(out, ty); + id(out, value); + } + V::Long(i) => { + out.extend(b"long"); + out.extend(i.to_be_bytes()); + } + V::Doub(d) => { + out.extend(b"doub"); + out.extend(d.to_be_bytes()); + } + V::UntF(unit, d) => { + out.extend(b"UntF"); + out.extend(*unit); + out.extend(d.to_be_bytes()); + } + V::Objc(class, items) => { + out.extend(b"Objc"); + descriptor(out, class, items); + } + V::Raw(data) => { + out.extend(b"tdta"); + out.extend((data.len() as u32).to_be_bytes()); + out.extend(data); + } + } + } +} + +/// The PostScript name of the face the text is drawn with (the style's font version when that is +/// installed), as type layers name fonts; without the face installed, its family and style without +/// spaces. +fn postscript(s: &CharStyle) -> String { + if let Some(face) = face(s) { + return face.postscript_name(); + } + let squeeze = |s: &str| -> String { s.chars().filter(|c| c.is_ascii_graphic() && !"[](){}<>/%".contains(*c)).collect() }; + match s.font_style.as_str() { + "" | "Regular" => squeeze(&s.font_family), + style => format!("{}-{}", squeeze(&s.font_family), squeeze(style)), + } +} + +/// The character attributes of `s` at `px` pixels per point, its font being `font` in the font set. +fn style_data(s: &CharStyle, font: usize, px: f64) -> E { + let rgb = match &s.fill { + Paint::Solid { color, .. } => color.to_rgb(), + _ => [0.0; 3], + }; + E::Dict(vec![ + ("Font", E::Int(font as i64)), + ("FontSize", E::Real(s.size * px)), + ("FauxBold", E::Bool(false)), + ("FauxItalic", E::Bool(false)), + ("AutoLeading", E::Bool(s.leading.is_none())), + ("Leading", E::Real(s.leading.unwrap_or(0.0) * px)), + ("HorizontalScale", E::Real(s.h_scale / 100.0)), + ("VerticalScale", E::Real(s.v_scale / 100.0)), + ("Tracking", E::Int(s.tracking.round() as i64)), + ("AutoKerning", E::Bool(true)), + ("Kerning", E::Int(0)), + ("BaselineShift", E::Real(s.baseline_shift * px)), + ("FontCaps", E::Int(if s.all_caps { 2 } else { 0 })), + ("Underline", E::Bool(s.underline)), + ("Strikethrough", E::Bool(s.strikethrough)), + ("FillFlag", E::Bool(true)), + ("FillColor", E::Dict(vec![("Type", E::Int(1)), ("Values", E::Array([1.0, rgb[0], rgb[1], rgb[2]].map(|v| E::Real(f64::from(v))).into()))])), + ]) +} + +/// The paragraph attributes of alignment `j`. +fn paragraph_data(j: Justify) -> E { + let n = match j { + Justify::Auto | Justify::Left => 0, + Justify::Right => 1, + Justify::Center => 2, + Justify::JustifyLeft => 3, + Justify::JustifyRight => 4, + Justify::JustifyCenter => 5, + Justify::JustifyAll => 6, + }; + E::Dict(vec![("Justification", E::Int(n)), ("AutoLeading", E::Real(1.2)), ("LeadingType", E::Int(0))]) +} + +/// The anti-aliasing method `aa` as the text descriptor's `AntA` value and the `EngineData` +/// `AntiAlias` number. +fn anti_alias(aa: TypeAntiAlias) -> (&'static str, i64) { + match aa { + TypeAntiAlias::None => ("Anno", 0), + TypeAntiAlias::Crisp => ("AnCr", 1), + TypeAntiAlias::Strong => ("AnSt", 2), + TypeAntiAlias::Sharp => ("AnSh", 4), + } +} + +/// The `EngineData` of `t` at `px` pixels per point, drawn with anti-aliasing `aa`: the text with a +/// `\r` after each paragraph, a style run per text run and a paragraph run per paragraph (lengths in +/// UTF-16 units), point type's shape, and the fonts. +fn engine_data(t: &TextObject, px: f64, aa: TypeAntiAlias) -> Vec { + let text = t.plain_text().replace('\n', "\r"); + let mut fonts: Vec = vec![]; + let (mut styles, mut lengths) = (vec![], vec![]); + let runs: Vec<_> = t.runs.iter().filter(|r| !r.text.is_empty()).collect(); + for (i, r) in runs.iter().enumerate() { + let name = postscript(&r.style); + let font = fonts.iter().position(|f| *f == name).unwrap_or_else(|| { + fonts.push(name); + fonts.len() - 1 + }); + styles.push(E::Dict(vec![("StyleSheet", E::Dict(vec![("StyleSheetData", style_data(&r.style, font, px))]))])); + // The closing `\r` belongs to the last run. + lengths.push(E::Int(r.text.encode_utf16().count() as i64 + i64::from(i + 1 == runs.len()))); + } + let (mut paras, mut para_lengths) = (vec![], vec![]); + for (i, p) in text.split('\r').enumerate() { + paras.push(E::Dict(vec![( + "ParagraphSheet", + E::Dict(vec![("DefaultStyleSheet", E::Int(0)), ("Properties", paragraph_data(t.para_at(i).justify))]), + )])); + para_lengths.push(E::Int(p.encode_utf16().count() as i64 + 1)); + } + let (writing, procession) = if t.vertical { (2, 1) } else { (0, 0) }; + let point = |x: f64, y: f64| E::Array(vec![E::Real(x), E::Real(y)]); + let shape = E::Dict(vec![ + ("ShapeType", E::Int(0)), + ("Procession", E::Int(procession)), + ("Lines", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![]))])), + ( + "Cookie", + E::Dict(vec![( + "Photoshop", // brand-ok: the key's name in the files + E::Dict(vec![ + ("ShapeType", E::Int(0)), + ("PointBase", point(0.0, 0.0)), + ( + "Base", + E::Dict(vec![ + ("ShapeType", E::Int(0)), + ("TransformPoint0", point(1.0, 0.0)), + ("TransformPoint1", point(0.0, 1.0)), + ("TransformPoint2", point(0.0, 0.0)), + ]), + ), + ]), + )]), + ), + ]); + let first = runs.first().map_or_else(|| style_data(&CharStyle::default(), 0, px), |r| style_data(&r.style, 0, px)); + let resources = || { + E::Dict(vec![ + ( + "FontSet", + E::Array( + fonts + .iter() + .map(|f| E::Dict(vec![("Name", E::Str(f.clone())), ("Script", E::Int(0)), ("FontType", E::Int(1)), ("Synthetic", E::Int(0))])) + .collect(), + ), + ), + ("StyleSheetSet", E::Array(vec![E::Dict(vec![("Name", E::Str("Normal RGB".into())), ("StyleSheetData", E::Dict(vec![]))])])), + ( + "ParagraphSheetSet", + E::Array(vec![E::Dict(vec![ + ("Name", E::Str("Normal RGB".into())), + ("DefaultStyleSheet", E::Int(0)), + ("Properties", paragraph_data(Justify::Left)), + ])]), + ), + ("TheNormalStyleSheet", E::Int(0)), + ("TheNormalParagraphSheet", E::Int(0)), + ]) + }; + let mut normal = resources(); + // The normal style sheet holds the first run's attributes. + if let E::Dict(items) = &mut normal + && let Some((_, E::Array(sheets))) = items.iter_mut().find(|(k, _)| *k == "StyleSheetSet") + && let Some(E::Dict(sheet)) = sheets.first_mut() + && let Some((_, data)) = sheet.iter_mut().find(|(k, _)| *k == "StyleSheetData") + { + *data = first; + } + let doc = E::Dict(vec![ + ( + "EngineDict", + E::Dict(vec![ + ("Editor", E::Dict(vec![("Text", E::Str(format!("{text}\r")))])), + ("ParagraphRun", E::Dict(vec![("RunArray", E::Array(paras)), ("RunLengthArray", E::Array(para_lengths)), ("IsJoinable", E::Int(1))])), + ("StyleRun", E::Dict(vec![("RunArray", E::Array(styles)), ("RunLengthArray", E::Array(lengths)), ("IsJoinable", E::Int(2))])), + ("AntiAlias", E::Int(anti_alias(aa).1)), + ("UseFractionalGlyphWidths", E::Bool(t.fractional_widths)), + ( + "Rendered", + E::Dict(vec![ + ("Version", E::Int(1)), + ("Shapes", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![shape]))])), + ]), + ), + ]), + ), + ("ResourceDict", resources()), + ("DocumentResources", normal), + ]); + let mut out = b"\n\n".to_vec(); + doc.write(0, &mut out); + out.push(b'\n'); + out +} + +/// The `TySh` block of point type `t`, drawn into a canvas whose top left is `origin` (document +/// points) at `px` pixels per point with anti-aliasing `aa`; `ink` is what the layer paints, in +/// canvas pixels. The transform maps the text's own space, in pixels with its origin at the first +/// baseline's start, to the canvas. +pub(super) fn type_block(t: &TextObject, origin: Point, px: f64, ink: Rect, aa: TypeAntiAlias) -> Vec { + let [a, b, c, d, e, f] = t.xf.as_coeffs(); + let xf = Affine::new([a, b, c, d, (e - origin.x) * px, (f - origin.y) * px]); + // The ink in text space: the canvas rectangle taken back through the transform. + let bounds = if xf.determinant().abs() > 1e-12 && [ink.x0, ink.y0, ink.x1, ink.y1].iter().all(|v| v.is_finite()) { + let inv = xf.inverse(); + let pts = [(ink.x0, ink.y0), (ink.x1, ink.y0), (ink.x0, ink.y1), (ink.x1, ink.y1)].map(|(x, y)| inv * Point::new(x, y)); + let (xs, ys) = (pts.map(|p| p.x), pts.map(|p| p.y)); + let (min, max) = (|v: [f64; 4]| v.into_iter().fold(f64::INFINITY, f64::min), |v: [f64; 4]| v.into_iter().fold(f64::NEG_INFINITY, f64::max)); + [min(xs), min(ys), max(xs), max(ys)] + } else { + [0.0; 4] + }; + let rect = |class: &'static str| { + V::Objc( + class, + vec![ + ("Left", V::UntF(b"#Pnt", bounds[0])), + ("Top ", V::UntF(b"#Pnt", bounds[1])), + ("Rght", V::UntF(b"#Pnt", bounds[2])), + ("Btom", V::UntF(b"#Pnt", bounds[3])), + ], + ) + }; + let orientation = if t.vertical { "Vrtc" } else { "Hrzn" }; + let mut out = 1u16.to_be_bytes().to_vec(); + for v in xf.as_coeffs() { + out.extend(v.to_be_bytes()); + } + // Text version 50, descriptor version 16. + out.extend(50u16.to_be_bytes()); + out.extend(16u32.to_be_bytes()); + descriptor( + &mut out, + "TxLr", + &[ + ("Txt ", V::Text(t.plain_text().replace('\n', "\r"))), + ("textGridding", V::Enum("textGridding", "None")), + ("Ornt", V::Enum("Ornt", orientation)), + ("AntA", V::Enum("Annt", anti_alias(aa).0)), + ("bounds", rect("bounds")), + ("boundingBox", rect("boundingBox")), + ("TextIndex", V::Long(0)), + ("EngineData", V::Raw(engine_data(t, px, aa))), + ], + ); + // Warp version 1, descriptor version 16: no warp. + out.extend(1u16.to_be_bytes()); + out.extend(16u32.to_be_bytes()); + descriptor( + &mut out, + "warp", + &[ + ("warpStyle", V::Enum("warpStyle", "warpNone")), + ("warpValue", V::Doub(0.0)), + ("warpPerspective", V::Doub(0.0)), + ("warpPerspectiveOther", V::Doub(0.0)), + ("warpRotate", V::Enum("Ornt", "Hrzn")), + ], + ); + // The warped bounds: zeros without a warp. + out.extend([0u8; 16]); + out +} diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index e2df72e01c..ae8836aa66 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -58,6 +58,8 @@ struct Rec { opacity: u8, hidden: bool, divider: Option, + /// The type tool object of a type layer. + type_tool: Option>, } /// The file: header channels, colour mode, image resources, layer count and records. @@ -95,7 +97,7 @@ fn parse(f: &[u8]) -> Parsed<'_> { let end = p + 16 + u32_at(f, p + 12); let mut q = p + 16 + 8; q += (1 + f[q] as usize).next_multiple_of(4); - let (mut name, mut divider) = (String::new(), None); + let (mut name, mut divider, mut type_tool) = (String::new(), None, None); while q < end { assert_eq!(&f[q..q + 4], b"8BIM"); let len = u32_at(f, q + 8); @@ -103,11 +105,12 @@ fn parse(f: &[u8]) -> Parsed<'_> { match &f[q + 4..q + 8] { b"luni" => name = String::from_utf16(&(0..u32_at(data, 0)).map(|i| u16_at(data, 4 + i * 2)).collect::>()).unwrap(), b"lsct" => divider = Some(u32_at(data, 0)), + b"TySh" => type_tool = Some(data.to_vec()), _ => {} } q += 12 + len; } - out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider }); + out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider, type_tool }); p = end; } out @@ -357,6 +360,373 @@ fn the_profile_and_the_size_limit() { assert!(err.contains(&MAX_SIDE.to_string()), "{err}"); } +/// A descriptor value as the format's specification lays it out. +#[derive(Debug, PartialEq)] +enum Item { + Text(String), + Enum(String, String), + Long(i32), + Doub(f64), + Unit(String, f64), + Object(String, Vec<(String, Item)>), + Raw(Vec), +} + +/// Reads an id (a four-character code after a zero length, else a length and its bytes) at `at`. +fn read_id(d: &[u8], at: &mut usize) -> String { + let n = u32_at(d, *at); + let len = if n == 0 { 4 } else { n }; + let s = String::from_utf8(d[*at + 4..*at + 4 + len].to_vec()).unwrap(); + *at += 4 + len; + s +} + +fn read_unicode(d: &[u8], at: &mut usize) -> String { + let n = u32_at(d, *at); + let units: Vec = (0..n).map(|i| u16_at(d, *at + 4 + i * 2)).collect(); + *at += 4 + n * 2; + String::from_utf16(&units).unwrap().trim_end_matches('\0').to_string() +} + +/// Reads a descriptor at `at`: its class and items. +fn read_descriptor(d: &[u8], at: &mut usize) -> (String, Vec<(String, Item)>) { + read_unicode(d, at); + let class = read_id(d, at); + let count = u32_at(d, *at); + *at += 4; + let mut items = vec![]; + for _ in 0..count { + let key = read_id(d, at); + let ty = d[*at..*at + 4].to_vec(); + *at += 4; + let f64_at = |at: usize| f64::from_be_bytes(d[at..at + 8].try_into().unwrap()); + let v = match &ty[..] { + b"TEXT" => Item::Text(read_unicode(d, at)), + b"enum" => Item::Enum(read_id(d, at), read_id(d, at)), + b"long" => { + *at += 4; + Item::Long(u32_at(d, *at - 4) as i32) + } + b"doub" => { + *at += 8; + Item::Doub(f64_at(*at - 8)) + } + b"UntF" => { + let unit = String::from_utf8(d[*at..*at + 4].to_vec()).unwrap(); + *at += 12; + Item::Unit(unit, f64_at(*at - 8)) + } + b"Objc" => { + let (class, items) = read_descriptor(d, at); + Item::Object(class, items) + } + b"tdta" => { + let n = u32_at(d, *at); + *at += 4 + n; + Item::Raw(d[*at - n..*at].to_vec()) + } + other => panic!("unexpected item type {other:?}"), + }; + items.push((key, v)); + } + (class, items) +} + +/// A type tool object: its transform, its text descriptor and its warp descriptor. +struct TypeTool { + transform: [f64; 6], + text: Vec<(String, Item)>, + warp: (String, Vec<(String, Item)>), +} + +fn type_tool(d: &[u8]) -> TypeTool { + assert_eq!(u16_at(d, 0), 1, "version"); + let transform = std::array::from_fn(|i| f64::from_be_bytes(d[2 + i * 8..10 + i * 8].try_into().unwrap())); + assert_eq!((u16_at(d, 50), u32_at(d, 52)), (50, 16), "text and descriptor versions"); + let mut at = 56; + let (class, text) = read_descriptor(d, &mut at); + assert_eq!(class, "TxLr"); + assert_eq!((u16_at(d, at), u32_at(d, at + 2)), (1, 16), "warp and descriptor versions"); + at += 6; + let warp = read_descriptor(d, &mut at); + assert_eq!(d.len(), (at + 16).next_multiple_of(2), "the four warped bounds end the block (padded to an even length)"); + TypeTool { transform, text, warp } +} + +fn item<'a>(items: &'a [(String, Item)], key: &str) -> &'a Item { + &items.iter().find(|(k, _)| k == key).unwrap_or_else(|| panic!("no {key}")).1 +} + +/// `s` as the text engine stores a string: UTF-16BE after a byte order mark. +fn engine_string(s: &str) -> Vec { + [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)).collect() +} + +fn type_node(b: &mut DocBuilder, origin: (f64, f64), text: &str, f: impl FnOnce(&mut vectorcraft_doc::TextObject)) -> Node { + use vectorcraft_doc::{CharStyle, NodeKind, TextObject}; + let style = CharStyle { size: 12.0, fill: vectorcraft_color::Paint::solid(Color::rgb8(0, 0, 0)), ..CharStyle::default() }; + let mut t = TextObject::point(vectorcraft_geom::Point::new(origin.0, origin.1), text, style); + f(&mut t); + Node::new(b.alloc(), NodeKind::Text(Box::new(t))) +} + +/// Layer 1: a red square, point type, a blue square. +fn type_doc() -> Document { + let mut b = DocBuilder::new(100.0, 60.0); + b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {}); + let t = type_node(&mut b, (20.0, 40.0), "Hi\nyou", |_| {}); + b.add(t); + b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {}); + b.build() +} + +#[test] +fn preserve_text_writes_point_type_as_a_type_layer_between_pixel_layers() { + let doc = type_doc(); + let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }) }; + let file = export(&doc, &o); + let p = parse(&file); + let rows: Vec<(&str, Option, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.divider, r.type_tool.is_some())).collect(); + assert_eq!( + rows, + [ + ("", Some(3), false), + ("Layer 1", None, false), + ("Hi\nyou", None, true), + ("Layer 1", None, false), + ("Layer 1", Some(1), false), + ], + "the layer becomes a group: the art below the type, the type layer, the art above it" + ); + assert_eq!(p.records[1].rect, [0, 0, 60, 60], "the red square alone, at 2 pixels a point"); + assert_eq!(p.records[3].rect, [20, 120, 80, 180], "the blue square alone"); + assert_ne!(p.records[2].rect, [0; 4], "the type layer keeps its pixels"); + + let t = type_tool(p.records[2].type_tool.as_deref().unwrap()); + assert_eq!(t.transform, [1.0, 0.0, 0.0, 1.0, 40.0, 80.0], "the first baseline's start, in pixels"); + assert_eq!(item(&t.text, "Txt "), &Item::Text("Hi\ryou".into())); + assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Hrzn".into())); + let Item::Object(_, bounds) = item(&t.text, "bounds") else { panic!("bounds") }; + let [l, top, r, bottom] = ["Left", "Top ", "Rght", "Btom"].map(|k| match item(bounds, k) { + Item::Unit(_, v) => *v, + other => panic!("{other:?}"), + }); + assert!(l < 4.0 && top < 0.0 && r > l && bottom > 24.0, "the ink around the baselines: {l} {top} {r} {bottom}"); + assert_eq!(t.warp.0, "warp"); + assert_eq!(item(&t.warp.1, "warpStyle"), &Item::Enum("warpStyle".into(), "warpNone".into())); + + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + let has = |needle: &[u8]| engine.windows(needle.len()).any(|w| w == needle); + assert!(has(&engine_string("Hi\ryou\r")), "the text ends with a paragraph break"); + assert!(has(b"/FontSize 24.0"), "the size in pixels at 144 ppi"); + assert!(has(b"/RunLengthArray [ 3 4 ]"), "a paragraph run per paragraph, breaks counted"); + assert!(has(b"/RunLengthArray [ 7 ]"), "one style run over the text and the closing break"); + assert!(has(b"/Values [ 1.0 0.0 0.0 0.0 ]"), "black"); + assert!(has(b"/ShapeType 0"), "point type"); + assert!(has(b"/UseFractionalGlyphWidths true"), "Fractional Widths on"); + + // A reader takes the file, and the merged image is the same render. + assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().layers().len(), p.records.len()); + let plain = export(&doc, &RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) }); + assert_eq!(merged(&file), merged(&plain)); + assert_eq!(parse(&plain).records.iter().filter(|r| r.type_tool.is_some()).count(), 0, "off: no type layers"); +} + +#[test] +fn type_a_type_layer_cant_draw_stays_pixels() { + use vectorcraft_doc::{NodeKind, TextKind}; + use vectorcraft_geom::PathData; + let mut b = DocBuilder::new(100.0, 60.0); + let area = type_node(&mut b, (10.0, 20.0), "Area", |t| { + t.kind = TextKind::Area { frame: PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(5.0, 5.0, 60.0, 50.0), 0.1)) }; + }); + b.add(area); + let stroked = type_node(&mut b, (10.0, 50.0), "Stroked", |t| { + t.runs[0].style.stroke = vectorcraft_color::Paint::solid(Color::rgb8(255, 0, 0)); + t.runs[0].style.stroke_width = 1.0; + }); + b.add(stroked); + let kerned = type_node(&mut b, (40.0, 50.0), "Kerned", |t| t.runs[0].style.kerning = Some(50.0)); + b.add(kerned); + let indented = type_node(&mut b, (70.0, 50.0), "Indented", |t| t.para.first_line_indent = 4.0); + b.add(indented); + let listed = type_node(&mut b, (10.0, 35.0), "Listed", |t| t.para.list = Some(vectorcraft_doc::text::ParaList::default())); + b.add(listed); + let system = type_node(&mut b, (40.0, 35.0), "System", |t| t.system_layout = true); + b.add(system); + let hanging = type_node(&mut b, (70.0, 35.0), "\"Hung\"", |t| t.optical_margin = true); + b.add(hanging); + let tabbed = type_node(&mut b, (10.0, 10.0), "a\tb", |t| { + t.para.tabs = vec![vectorcraft_doc::TabStop { position: 30.0, align: Default::default(), leader: String::new(), align_on: '.' }]; + }); + b.add(tabbed); + let leading = type_node(&mut b, (40.0, 10.0), "Auto", |t| t.para.justification.auto_leading = 150.0); + b.add(leading); + let standard = type_node(&mut b, (40.0, 20.0), "Std", |t| t.para.composer = vectorcraft_doc::Composer::StandardEveryLine); + b.add(standard); + // Hebrew: right to left from its first strong character, so Auto alignment is right. In an + // installed font that covers it when there is one; otherwise its font lacks it. + let hebrew_face = vectorcraft_text::FontDb::global().face_covering('ש'); + let hebrew = type_node(&mut b, (70.0, 10.0), "שלום", |t| { + if let Some(f) = &hebrew_face { + (t.runs[0].style.font_family, t.runs[0].style.font_style) = (f.family.clone(), f.style.clone()); + } + }); + b.add(hebrew); + let tracked = type_node(&mut b, (10.0, 58.0), "Tracked", |t| t.runs[0].style.tracking = 0.5); + b.add(tracked); + let british = type_node(&mut b, (70.0, 58.0), "Colour", |t| t.runs[0].style.language = Some("en-GB".into())); + b.add(british); + // Drawn partly with a fallback font: the bundled fonts have no 縦. + let fallback = type_node(&mut b, (40.0, 58.0), "A縦", |_| {}); + b.add(fallback); + let mut doc = b.build(); + let with = |o: PsdOptions| export(&doc, &opts(o)); + assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way"); + + // An empty point type object has no text to edit. + let empty = Node::new( + doc.alloc_id(), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "", Default::default()))), + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, empty).unwrap(); + let file = export(&doc, &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() })); + assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none())); +} + +#[test] +fn vertical_type_and_maximum_editability() { + let mut b = DocBuilder::new(100.0, 60.0); + b.rect(Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb8(255, 0, 0), |_| {}); + let t = type_node(&mut b, (50.0, 10.0), "Up", |t| t.vertical = true); + b.add(t); + let hidden = type_node(&mut b, (10.0, 50.0), "Hidden", |_| {}); + b.add(Node { visible: false, ..hidden }); + let doc = b.build(); + let o = opts(PsdOptions { preserve_text: true, max_editability: true, hidden_layers: true, ..PsdOptions::default() }); + let file = export(&doc, &o); + let p = parse(&file); + let rows: Vec<(&str, bool, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.type_tool.is_some(), r.hidden)).collect(); + let square = doc.layers[0].children().unwrap()[0].display_name(); + assert_eq!( + rows, + [("", false, false), (square.as_str(), false, false), ("Up", true, false), ("Hidden", true, true), ("Layer 1", false, false)], + "each object a layer of its own; hidden type is a hidden type layer" + ); + let t = type_tool(p.records[2].type_tool.as_deref().unwrap()); + assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Vrtc".into())); + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + assert!(engine.windows(19).any(|w| w == b"/WritingDirection 2"), "vertical writing"); +} + +#[test] +fn type_layer_keeps_fractional_widths_off() { + let mut b = DocBuilder::new(100.0, 60.0); + let t = type_node(&mut b, (10.0, 30.0), "Whole", |t| t.fractional_widths = false); + b.add(t); + let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() })); + let p = parse(&file); + let record = p.records.iter().find(|r| r.type_tool.is_some()).expect("a type layer"); + let t = type_tool(record.type_tool.as_deref().unwrap()); + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + let needle = b"/UseFractionalGlyphWidths false"; + assert!(engine.windows(needle.len()).any(|w| w == needle), "whole-point advances, as the pixels are drawn"); +} + +#[test] +fn type_layer_keeps_the_anti_aliasing_method() { + use vectorcraft_doc::text::TypeAntiAlias; + let engine_anti_alias = |doc: &Document, o: &RasterExportOptions| { + let file = export(doc, o); + let p = parse(&file); + let t = type_tool(p.records.iter().find_map(|r| r.type_tool.as_deref()).expect("a type layer")); + let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") }; + let at = engine.windows(11).position(|w| w == b"/AntiAlias ").expect("AntiAlias"); + let Item::Enum(_, method) = item(&t.text, "AntA") else { panic!("AntA") }; + (method.clone(), engine[at + 11]) + }; + let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }); + for (aa, key, number) in [ + (TypeAntiAlias::None, "Anno", b'0'), + (TypeAntiAlias::Sharp, "AnSh", b'4'), + (TypeAntiAlias::Crisp, "AnCr", b'1'), + (TypeAntiAlias::Strong, "AnSt", b'2'), + ] { + let mut b = DocBuilder::new(100.0, 60.0); + let t = type_node(&mut b, (10.0, 30.0), "Edges", |t| t.anti_alias = aa); + b.add(t); + let doc = b.build(); + assert_eq!(engine_anti_alias(&doc, &o), (key.to_string(), number), "{aa:?}"); + let hard = RasterExportOptions { anti_alias: crate::AntiAlias::None, ..o.clone() }; + assert_eq!(engine_anti_alias(&doc, &hard), ("Anno".to_string(), b'0'), "{aa:?} exported without anti-aliasing"); + } +} + +#[test] +fn variation_selectors_and_joiners_need_no_glyph() { + let mut b = DocBuilder::new(100.0, 60.0); + // In English: USA, the default language, given by its tag. + let t = type_node(&mut b, (10.0, 30.0), "A\u{FE0F}\u{200D}B\u{E0100}", |t| t.runs[0].style.language = Some("en-US".into())); + b.add(t); + let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() })); + assert_eq!(parse(&file).records.iter().filter(|r| r.type_tool.is_some()).count(), 1); +} + +#[test] +fn hidden_type_left_out_keeps_its_layer_whole() { + let mut b = DocBuilder::new(100.0, 60.0); + b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {}); + let t = type_node(&mut b, (20.0, 40.0), "Hidden", |_| {}); + b.add(Node { visible: false, ..t }); + b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {}); + let doc = b.build(); + let with = |o: PsdOptions| export(&doc, &opts(o)); + assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way"); + let shown = parse(&with(PsdOptions { preserve_text: true, hidden_layers: true, ..PsdOptions::default() })) + .records + .iter() + .filter(|r| r.type_tool.is_some() && r.hidden) + .count(); + assert_eq!(shown, 1, "with hidden layers: a hidden type layer"); +} + +#[test] +fn blending_art_keeps_its_layer_whole() { + use vectorcraft_color::BlendMode; + use vectorcraft_doc::AppearanceItem; + // The square's blend mode, on the object (`fill`: false) or on its fill. + let build = |blend: BlendMode, above: bool, fill: bool| { + let mut b = DocBuilder::new(100.0, 60.0); + let square = |b: &mut DocBuilder| { + b.rect(Rect::new(0.0, 0.0, 60.0, 40.0), Color::rgb8(255, 0, 0), |n| { + if !fill { + n.blend = blend; + } else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.blend = blend; + } + }); + }; + if !above { + square(&mut b); + } + let t = type_node(&mut b, (10.0, 30.0), "Type", |_| {}); + b.add(t); + if above { + square(&mut b); + } + b.build() + }; + let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }); + for (above, fill) in [(true, false), (false, false), (true, true)] { + let normal = export(&build(BlendMode::Normal, above, fill), &o); + assert_eq!(parse(&normal).records.iter().filter(|r| r.type_tool.is_some()).count(), 1, "normal art (above: {above}): a type layer"); + let doc = build(BlendMode::Multiply, above, fill); + let file = export(&doc, &o); + assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none()), "multiplied art (above: {above}, fill: {fill}): one pixel layer"); + assert_eq!(file, export(&doc, &opts(PsdOptions::default()))); + } +} + #[test] fn long_unicode_name_is_cut_on_a_character_boundary() { let mut b = DocBuilder::new(100.0, 60.0); diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index e6400c90af..8e0a40ef43 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -688,6 +688,16 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); + // Copies that each carry the raster effects listed before their Transform effect reach + // as far as each copy's raster effects paint, and the raster effects after it spread + // them all: the art and each copy in it are groups with those raster effects, measured + // with their reach ([`effects::has_container_appearance`]). + if effects::outer_effects(n).len() < n.appearance.effects.len() + && let Some(r) = &reshaped + { + let a = live_content_reach(symbols, n); + return cull_bounds_in(symbols, r, after_reshape, false).map(|b| b.inflate(a, a)); + } let b = match &reshaped { Some(r) if has_instance_row_effects(n) => instance_piece_bounds(symbols, r), Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => { diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 37f3fbf4f7..8e18b3a045 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -653,7 +653,20 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; - for c in shapes { + // An Abutting trace's seam fills hold no traced outline: a clip group of paths that are + // each stroked without a fill or (on a stretched image, the strokes' outlines) filled + // without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the + // trace puts it. + let seam_fills = |i: usize, c: &Arc| { + let one_paint = |m: &Arc| { + matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && m.appearance.fill_paint().is_none() != m.appearance.stroke_paint().is_none() + }; + (i == 0 || c.name.as_deref() == Some("Seam Fills")) + && matches!(&c.kind, NodeKind::Group { clip: true, children } + if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(one_paint))) + }; + for (_, c) in shapes.iter().enumerate().filter(|(i, c)| !seam_fills(*i, c)) { self.draw_outline_member(ctx, &frame, c); } } diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index f93124e1b9..9f145cae2a 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1242,3 +1242,45 @@ fn each_copy_of_a_transform_effect_draws_its_own_shadow() { let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap(); assert!(b.x1 >= 80.0 - 1e-9, "{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 +/// its right. +#[test] +fn each_copy_of_an_images_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 50, "scaleV": 50, "moveV": 40, "copies": 1})); + let img = render(&image_doc(vec![shadow, copies])); + assert_eq!(img.pixel(35, 35), [255, 0, 0, 255], "the image"); + assert_eq!(img.pixel(55, 35), [0, 255, 0, 255], "the image's shadow"); + assert_eq!(img.pixel(35, 75), [255, 0, 0, 255], "the copy"); + assert_eq!(img.pixel(45, 75), [0, 255, 0, 255], "the copy's shadow, 5 pt to its right"); + assert_eq!(img.pixel(50, 75), [255, 255, 255, 255], "past the copy's shadow"); +} + +/// Each copy of a symbol instance's Transform effect draws the drop shadow listed before the effect +/// under itself, scaled with it: the black square (40..60) has its green shadow 10 pt to its right, +/// and its copy scaled 150 % and moved 30 pt down (35..65 across, 65..95 down) has its own 15 pt to +/// its right. The bounds reach as far as the copy's shadow, and as far as a shadow listed after the +/// Transform effect paints below all of them. +#[test] +fn each_copy_of_a_symbol_instances_transform_effect_draws_its_own_shadow() { + let shadow = fx("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"})); + let copies = fx("distort.transform", json!({"scaleH": 150, "scaleV": 150, "moveV": 30, "copies": 1})); + let below = fx("stylize.dropShadow", json!({"x": 0, "y": 20, "blur": 0, "opacity": 100, "mode": "normal", "color": "#0000ff"})); + let d = symbol_doc(vec![shadow.clone(), copies.clone(), below]); + let n = &d.layers[0].children().unwrap()[0]; + let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), n).unwrap(); + assert!(b.x1 >= 80.0 - 1e-9 && b.y1 >= 115.0 - 1e-9, "{b:?}"); + let d = symbol_doc(vec![shadow, copies]); + let img = render(&d); + assert_eq!(img.pixel(50, 50), [0, 0, 0, 255], "the instance"); + assert_eq!(img.pixel(65, 50), [0, 255, 0, 255], "the instance's shadow"); + assert_eq!(img.pixel(50, 80), [0, 0, 0, 255], "the copy"); + assert_eq!(img.pixel(77, 80), [0, 255, 0, 255], "the copy's shadow, 15 pt to its right"); + assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "past the copy's shadow"); + let n = &d.layers[0].children().unwrap()[0]; + let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), n).unwrap(); + assert!(b.x1 >= 80.0 - 1e-9, "{b:?}"); +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index b45564c887..b0b59eb886 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -70,7 +70,7 @@ pub use stylistic_sets::StylisticSet; use traits::Alias; #[cfg(test)] use traits::{FaceKeys, face_names}; -pub use traits::{FontClass, FontMatch, FontTraits}; +pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits}; #[cfg(test)] pub(crate) use traits::{alias_lists, face_styles, on_faces_published}; pub use wanted::{WantedFont, WantedFonts}; diff --git a/crates/text/src/fontdb/cache.rs b/crates/text/src/fontdb/cache.rs index 09b03c410c..72bed5519b 100644 --- a/crates/text/src/fontdb/cache.rs +++ b/crates/text/src/fontdb/cache.rs @@ -8,7 +8,10 @@ pub(super) struct CatalogFamily { /// Non-English family name from the name table, when the scan found one. pub(super) native: Option, pub(super) faces: Vec, - /// The family's kind (from its first face found); variable when any face found is. + /// The family's kind (from its first face found); variable when any face found is. Its + /// likeness is the one of the face found nearest an upright Regular ([`regular_rank`]). + /// + /// [`regular_rank`]: super::traits::regular_rank pub(super) traits: Option, } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 738a158952..e890e0c833 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -16,7 +16,7 @@ use super::scan::{file_face_names, is_font_file}; #[cfg(test)] use super::traits::faces_published; #[cfg(not(target_arch = "wasm32"))] -use super::traits::{Alias, FaceStyle}; +use super::traits::{Alias, FaceStyle, regular_rank}; use super::{Arc, AtomicU64, FontDb, FontPaths, HashMap, Mutex, Ordering, Path, PathBuf, RwLock, StringId}; #[cfg(not(target_arch = "wasm32"))] use super::{ScanStamp, modified}; @@ -430,6 +430,9 @@ impl FontDb { let entry = catalog.entry(family.to_ascii_lowercase()).or_default(); let kind = entry.traits.get_or_insert(traits); kind.variable |= traits.variable; + if regular_rank(&traits.likeness) < regular_rank(&kind.likeness) { + kind.likeness = traits.likeness; + } if entry.name.is_empty() { entry.name = family; } diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index ff9ad8d58f..5d90bf6976 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -356,6 +356,11 @@ impl FontFace { pub fn x_height(&self) -> f64 { self.x_height } + /// The height of the capital letters in font units, positive (estimated from the ascent when + /// the font has no OS/2 value). + pub fn cap_height(&self) -> f64 { + self.cap_height + } /// The line gap the font asks for between lines, in font units (from the same table as /// [`vertical_metrics`](Self::vertical_metrics); 0 when it has none). pub fn line_gap(&self) -> f64 { diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index a88d4ed86a..7529a82929 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -549,6 +549,13 @@ impl FontFace { self.gsub_index().by_input.get(&gid).cloned().unwrap_or_default() } + /// Do [`Self::substitutions`] of glyph `gid` give a glyph other than `gid` itself? It reads the + /// face's index without copying the substitutions, so the Glyphs panel asks it for each cell it + /// draws. + pub fn has_alternates(&self, gid: u32) -> bool { + self.gsub_index().by_input.get(&gid).is_some_and(|subs| subs.iter().any(|s| s.glyphs.iter().any(|&g| g != gid))) + } + /// The feature of the `GSUB` table that gives glyph `gid` as a substitute (by a single, /// multiple, alternate or ligature substitution), a listed feature ([`Self::substitutions`]) /// before another (`init`, `liga`), if any does. Not read through a contextual lookup. diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 23e00afa0c..597e8bbc6c 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -9,7 +9,7 @@ use super::names::SYSTEM_FALLBACKS; use super::names::{norm, norm_chars, script_families}; #[cfg(not(target_arch = "wasm32"))] use super::scan::{enumerate_faces, font_files}; -use super::traits::{Alias, FontMatch, FontTraits}; +use super::traits::{Alias, FontMatch, FontTraits, regular_rank}; use super::{ Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering, Size, @@ -18,6 +18,45 @@ use super::{ /// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads. const MAX_POSTSCRIPT_FACES: usize = 16; +/// Keeps `other`'s variable flag in `traits`, and its likeness when it is nearer an upright +/// Regular. +fn merge_traits(traits: &mut FontTraits, other: &FontTraits) { + traits.variable |= other.variable; + if regular_rank(&other.likeness) < regular_rank(&traits.likeness) { + traits.likeness = other.likeness; + } +} + +/// The traits of the loaded faces of each family, or of `only` that family, keyed by the family's +/// name in ASCII lowercase: the first face's, with the other faces merged in ([`merge_traits`]). +fn loaded_traits(faces: &[Arc], only: Option<&str>) -> std::collections::HashMap { + let mut found = std::collections::HashMap::::new(); + for f in faces.iter().filter(|f| only.is_none_or(|o| f.family.eq_ignore_ascii_case(o))) { + match found.entry(f.family.to_ascii_lowercase()) { + std::collections::hash_map::Entry::Vacant(e) => { + e.insert(f.traits); + } + std::collections::hash_map::Entry::Occupied(mut e) => merge_traits(e.get_mut(), &f.traits), + } + } + found +} + +/// A family's traits from its `loaded` faces with what the scan in `catalog` found for `key` (its +/// name in ASCII lowercase) merged in, or the scan's alone when none is loaded. +fn scanned_traits(loaded: Option, catalog: &Catalog, key: &str) -> FontTraits { + let scanned = catalog.get(key).and_then(|c| c.traits); + match loaded { + None => scanned.unwrap_or_default(), + Some(mut traits) => { + if let Some(found) = scanned { + merge_traits(&mut traits, &found); + } + traits + } + } +} + impl FontDb { /// The family's own name and the style for a name given in a document: any of a family's /// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its @@ -86,26 +125,73 @@ impl FontDb { /// loaded face, else from the system font scan. Variable when any of its faces, loaded or /// scanned, is: a family may install static files beside a variable one. Cheap: no font file /// is read, and a loaded family doesn't start the scan. A composite font takes its base font's. + /// Its likeness is the one of its face nearest an upright Regular, loaded or scanned. pub fn family_traits(&self, family: &str) -> FontTraits { if let Some((base, _)) = self.composite_base(family) { return self.family_traits(&base); } - let loaded = { - let faces = self.read_faces(); - let mut of_family = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)); - of_family.next().map(|first| FontTraits { variable: first.traits.variable || of_family.any(|f| f.traits.variable), ..first.traits }) - }; - let scanned = |catalog: &Catalog| catalog.get(&family.to_ascii_lowercase()).and_then(|c| c.traits); + let key = family.to_ascii_lowercase(); + let loaded = loaded_traits(&self.read_faces(), Some(family)).remove(&key); match loaded { - None => scanned(&self.read_catalog()).unwrap_or_default(), - Some(traits) if traits.variable => traits, - Some(traits) => { - let variable = scanned(&self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)).is_some_and(|t| t.variable); - FontTraits { variable, ..traits } - } + None => scanned_traits(None, &self.read_catalog(), &key), + // What the scan found so far, without starting it. + Some(_) => scanned_traits(loaded, &self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner), &key), } } + /// The name [`family_traits`](Self::family_traits) takes `family`'s traits by, in ASCII + /// lowercase: a composite font's base font's. + fn traits_key(&self, family: &str) -> String { + match self.composite_base(family) { + Some((base, _)) => self.traits_key(&base), + None => family.to_ascii_lowercase(), + } + } + + /// `families` ordered by how alike they look to `family` (Show Similar Fonts): `family` itself + /// first when listed, then the families that set the same script as it (Japanese, Thai or + /// neither, as [`FontTraits`] tells), then the others, each group nearest first by + /// [`FontLikeness::distance`](super::FontLikeness::distance) of their + /// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`]) + /// counting 2 further. Families equally far keep their order in `families`. Reads no font + /// file, as `family_traits` does not. + pub fn similar_families(&self, family: &str, families: &[String]) -> Vec { + let base = self.family_traits(family); + let script = |t: &FontTraits| { + if t.japanese { + 0 + } else if t.thai { + 1 + } else { + 2 + } + }; + // Every family's traits from one pass over the loaded faces and one look at the scan, as + // `family_traits` finds them; composite fonts are resolved before any lock is held. + let keys: Vec = families.iter().map(|f| self.traits_key(f)).collect(); + let loaded = loaded_traits(&self.read_faces(), None); + let catalog = if keys.iter().all(|k| loaded.contains_key(k)) { + self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner) + } else { + self.read_catalog() + }; + let mut keyed: Vec<(bool, f32, &String)> = families + .iter() + .zip(&keys) + .map(|(f, key)| { + let traits = scanned_traits(loaded.get(key).copied(), &catalog, key); + let d = if f.eq_ignore_ascii_case(family) { + -1.0 + } else { + base.likeness.distance(&traits.likeness) + if traits.class == base.class { 0.0 } else { 2.0 } + }; + (script(&traits) != script(&base), d, f) + }) + .collect(); + keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); + keyed.into_iter().map(|(_, _, f)| f.clone()).collect() + } + /// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how /// it matched. A composite font matches as its base font does ([`Self::composite_base`]). pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc, FontMatch)> { diff --git a/crates/text/src/fontdb/scan.rs b/crates/text/src/fontdb/scan.rs index ebe4d4d443..e25891fb32 100644 --- a/crates/text/src/fontdb/scan.rs +++ b/crates/text/src/fontdb/scan.rs @@ -160,6 +160,8 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa use std::io::SeekFrom; /// The largest table read from a (possibly damaged) file. const MAX_NAME_TABLE: u32 = 1 << 20; + /// The `post` table's header: version, italic angle, underline and fixed-pitch fields. + const POST_HEADER: u32 = 32; let mut read = 0u64; let mut read_at = |offset: u64, len: usize| -> Option> { read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?; @@ -186,26 +188,34 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) { return None; } - let mut table = |tag: &[u8; 4]| -> Option> { + // A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing. + let mut table_within = |tag: &[u8; 4], most: u32| -> Option> { let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?; - let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?); + let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most)); if len > MAX_NAME_TABLE { return None; } read_at(offset.into(), len as usize) }; - let name = table(b"name")?; + let name = table_within(b"name", u32::MAX)?; // A variable font's named instances are styles too. - let fvar = table(b"fvar"); + let fvar = table_within(b"fvar", u32::MAX); // Its OS/2 table (the font's classification, for the menus' filters), when it has one. - let os2 = table(b"OS/2"); + let os2 = table_within(b"OS/2", u32::MAX); + // Its units per em and italic angle, for Show Similar Fonts ([`super::FontLikeness`]): + // the `head` table and the `post` table's 32-byte header, as a version 3 table (one + // without glyph names). + let head = table_within(b"head", u32::MAX); + let post = table_within(b"post", POST_HEADER).filter(|p| p.len() == POST_HEADER as usize).map(|mut p| { + p[..4].copy_from_slice(&0x0003_0000_u32.to_be_bytes()); + p + }); // A font holding just these tables, to read them as the font itself would. let mut tables: Vec<(&[u8; 4], &[u8])> = vec![(b"name", &name)]; - if let Some(fvar) = &fvar { - tables.push((b"fvar", fvar)); - } - if let Some(os2) = &os2 { - tables.push((b"OS/2", os2)); + for (tag, data) in [(b"fvar", &fvar), (b"OS/2", &os2), (b"head", &head), (b"post", &post)] { + if let Some(data) = data { + tables.push((tag, data.as_slice())); + } } let font = sfnt_of(&tables)?; Some(face_styles(&skrifa::FontRef::new(&font).ok()?)) diff --git a/crates/text/src/fontdb/traits.rs b/crates/text/src/fontdb/traits.rs index b6244b81d9..335e4dba13 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -101,6 +101,111 @@ pub struct FontTraits { /// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of /// its faces has. pub variable: bool, + /// What Show Similar Fonts compares; for a family, its face nearest an upright Regular. + pub likeness: FontLikeness, +} + +/// The numbers a font menu's Show Similar Fonts compares faces by ([`FontLikeness::distance`]), +/// read from the face's OS/2, `head` and `post` tables only, so that the system font scan reads +/// the same numbers without loading the font ([`super::scan::file_face_names`]). Each is 0 (the +/// italic angle `None`) when the face does not say (no such table, or an OS/2 table too old to +/// hold the value). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FontLikeness { + /// The OS/2 PANOSE digits (0 is "any" and 1 "no fit" in each digit). + pub panose: [u8; 10], + /// The OS/2 weight class, at most 1000; a named instance's `wght` setting. + pub weight: u16, + /// The OS/2 width class, 1 to 9. + pub width: u8, + /// The OS/2 x-height and cap height in thousandths of the em. + pub x_height: u16, + pub cap_height: u16, + /// The OS/2 average character width in thousandths of the em. + pub avg_width: u16, + /// The `post` table's italic angle in tenths of a degree (negative: leaning right); a named + /// instance's `slnt` setting. + pub italic_angle: Option, + /// The face is italic or oblique: by its OS/2 selection flags or a nonzero italic angle; a + /// named instance by its `ital` or `slnt` setting or its name. Not compared; it picks a + /// family's face nearest an upright Regular. + pub italic: bool, +} + +impl FontLikeness { + /// From a face's tables, with a named instance's `variations` (its axis settings in user + /// units; empty for the face itself): its `weight` (`wght` setting) in place of the OS/2 + /// weight class, its `slnt` setting in place of the italic angle, and whether it is + /// `italic`. The heights and the average width need the `head` table's units per em (16 to + /// 16384). + fn of(font: &skrifa::FontRef<'_>, variations: &[Variation], weight: Option, italic: Option) -> Self { + use skrifa::raw::TableProvider; + let em = font.head().ok().map(|h| h.units_per_em()).filter(|u| (16..=16384).contains(u)).map(f32::from); + // Thousandths of the em, 0 for nothing (and for a value at or below 0). + let per_mille = |v: i16| match em { + Some(em) if v > 0 => (f32::from(v) / em * 1000.0).round().min(4000.0) as u16, + _ => 0, + }; + let mut likeness = Self::default(); + if let Ok(o) = font.os2() { + for (digit, value) in likeness.panose.iter_mut().zip(o.panose_10()) { + *digit = *value; + } + likeness.weight = o.us_weight_class().min(1000); + likeness.width = u8::try_from(o.us_width_class()).ok().filter(|w| (1..=9).contains(w)).unwrap_or(0); + likeness.x_height = o.sx_height().map_or(0, per_mille); + likeness.cap_height = o.s_cap_height().map_or(0, per_mille); + likeness.avg_width = per_mille(o.x_avg_char_width()); + // fsSelection's ITALIC (bit 0) and OBLIQUE (bit 9) flags. + likeness.italic = o.fs_selection().bits() & 0x0201 != 0; + } + if let Some(w) = weight.filter(|w| w.is_finite()) { + likeness.weight = w.round().clamp(1.0, 1000.0) as u16; + } + let angle = |a: f32| (a.is_finite() && a.abs() <= 90.0).then(|| (a * 10.0).round() as i16); + likeness.italic_angle = match variations.iter().find(|(tag, _)| tag == b"slnt") { + Some((_, slant)) => angle(*slant), + None => font.post().ok().and_then(|p| angle(p.italic_angle().to_f32())), + }; + likeness.italic = italic.unwrap_or(likeness.italic || likeness.italic_angle.is_some_and(|a| a != 0)); + likeness + } + + /// How unlike two faces look: 0 for faces whose numbers are all the same, more the further + /// apart they are. A number one of the faces does not give is left out. PANOSE digits are + /// compared only between faces of the same PANOSE family kind; faces of different kinds count + /// 3 apart. The weights and scales are VectorCraft's own. + pub fn distance(&self, other: &Self) -> f32 { + let mut d = 0.0; + let (kind, other_kind) = (self.panose[0], other.panose[0]); + if kind > 1 && other_kind > 1 { + if kind == other_kind { + for (a, b) in self.panose.iter().zip(&other.panose).skip(1) { + if *a > 1 && *b > 1 { + d += f32::from(a.abs_diff(*b)) * 0.15; + } + } + } else { + d += 3.0; + } + } + if self.weight != 0 && other.weight != 0 { + d += f32::from(self.weight.abs_diff(other.weight)) / 200.0; + } + if self.width != 0 && other.width != 0 { + d += f32::from(self.width.abs_diff(other.width)) * 0.5; + } + for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)] + { + if a != 0 && b != 0 { + d += f32::from(a.abs_diff(b)) / 1000.0 * scale; + } + } + if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) { + d += f32::from(a.abs_diff(b)) / 50.0; + } + d + } } impl FontTraits { @@ -216,10 +321,20 @@ impl FontTraits { FontClass::Other }; let variable = (1..=MAX_AXES).contains(&font.axes().len()); - FontTraits { japanese, thai, class, variable } + FontTraits { japanese, thai, class, variable, likeness: FontLikeness::of(font, &[], None, None) } } } +/// How far a face is from an upright Regular by its `likeness`: an italic or oblique face +/// ([`FontLikeness::italic`]) after every upright one, then by how far its weight is from 400 (a +/// face that gives no weight last), then by the numbers themselves, so that the same faces give +/// the same answer whichever is found or loaded first. The lower, the nearer. A family's likeness +/// ([`FontTraits::likeness`]) is its lowest-ranked face's, whether the faces are scanned or loaded. +pub(super) fn regular_rank(likeness: &FontLikeness) -> (bool, u16, FontLikeness) { + let off = if likeness.weight == 0 { u16::MAX } else { likeness.weight.abs_diff(400) }; + (likeness.italic, off, *likeness) +} + /// What a name other than a family's own one stands for ([`FontDb::canonical`]). #[derive(Clone, Debug)] pub(super) struct Alias { @@ -342,11 +457,7 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec { let Some((family, style)) = face_names(f) else { return vec![] }; let native_family = native_family_name(f, &family); let mut keys = FaceKeys::of(f, &family, &style); - let traits = FontTraits::of(f, &keys); - let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone()); - for i in &mut instances { - i.traits = traits; - } + let mut traits = FontTraits::of(f, &keys); // A variable font's default face renders at its `wght` default, whatever its name table and // OS/2 table say (Noto Sans Hebrew: named `Light`, weight class 300, default instance Regular // at 400): weigh it so, and name it by its default instance when that is another weight. @@ -357,6 +468,19 @@ pub(crate) fn face_styles(f: &skrifa::FontRef<'_>) -> Vec { .map(|a| a.default_value()) .filter(|w| w.is_finite()) .map(|w| w.clamp(1.0, 1000.0)); + // Its likeness is likewise taken at its axes' defaults (`wght` and `slnt`). + if f.axes().len() <= MAX_AXES { + let defaults: Vec = f.axes().iter().map(|a| (a.tag().to_be_bytes(), a.default_value())).collect(); + traits.likeness = FontLikeness::of(f, &defaults, weight, None); + } + let (mut instances, renamed) = named_instances(f, &family, &style, &mut keys, native_family.clone()); + // Each named instance shares the face's kind; its likeness is measured at its own axis settings. + // Without an `ital` or `slnt` axis, an instance of an italic face is italic too. + for i in &mut instances { + let slant_axis = i.variations.iter().any(|(tag, _)| tag == b"ital" || tag == b"slnt"); + let italic = i.italic || (!slant_axis && traits.likeness.italic); + i.traits = FontTraits { likeness: FontLikeness::of(f, &i.variations, i.weight, Some(italic)), ..traits }; + } let style = renamed.unwrap_or(style); let face = FaceStyle { family, native_family, style, keys, variations: vec![], weight, italic: false, traits }; std::iter::once(face).chain(instances).collect() diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 3c28bc3f25..8ab7732586 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -41,10 +41,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, GlyphCategoryKind, - GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, - WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, - style_weight, system_font_dirs, user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, + GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, + WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, + set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index c04200a94f..3905a42099 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -28,6 +28,7 @@ mod path_joins; mod ruby; mod scripts; mod shape_plans; +mod similar; mod snap; mod svg_glyphs; mod sysfonts; diff --git a/crates/text/src/tests/alternates.rs b/crates/text/src/tests/alternates.rs index cc70780eb3..48f621555d 100644 --- a/crates/text/src/tests/alternates.rs +++ b/crates/text/src/tests/alternates.rs @@ -40,6 +40,25 @@ fn alternates_come_in_feature_order_once_each() { assert!(bundled.alternates('a').iter().all(|a| a.gid < bundled.glyph_count())); } +/// A glyph has alternates when a listed feature gives it another glyph: `a` has them in both +/// faces, `b` and the alternates of `a` have none, and a glyph past the face has none. +#[test] +fn has_alternates_follows_the_listed_substitutions() { + let db = db(); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + for aalt in [true, false] { + let face = db.face(alternates_family(aalt), "Regular").expect("the test face"); + assert!(face.has_alternates(face.glyph_for('a')), "a, aalt {aalt}"); + assert!(!face.has_alternates(face.glyph_for('b')), "b, aalt {aalt}"); + assert!(!face.has_alternates(u1), "an alternate of a has none of its own, aalt {aalt}"); + assert!(!face.has_alternates(face.glyph_count() + 10), "a glyph past the face, aalt {aalt}"); + } + let bundled = db.face(FALLBACK_FAMILY, "Regular").expect("the bundled face"); + let with = bundled.chars().into_iter().filter(|(_, g)| bundled.has_alternates(*g)).count(); + let listed = bundled.chars().into_iter().filter(|(c, g)| bundled.alternates(*c).iter().any(|a| a.gid != *g)).count(); + assert_eq!(with, listed, "the same characters as the alternates lists say"); +} + /// The cap on lookups read in all leaves out the lowest ranked features: `salt` is read even when /// the `cv01` records before it list more lookups than the cap. #[test] diff --git a/crates/text/src/tests/similar.rs b/crates/text/src/tests/similar.rs new file mode 100644 index 0000000000..718f4607ea --- /dev/null +++ b/crates/text/src/tests/similar.rs @@ -0,0 +1,119 @@ +//! Show Similar Fonts: the numbers a face is compared by ([`FontLikeness`]), a family's likeness +//! from its face nearest an upright Regular, and families ordered by likeness. + +use skrifa::raw::TableProvider; + +use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font}; +use crate::*; + +/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without +/// heights in their OS/2 tables. +fn db() -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + for heights in [true, false] { + assert_eq!(db.add_font(height_font(heights).expect("the test font builds")), 1); + } + db +} + +fn names(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn a_face_is_compared_by_its_tables() { + let db = db(); + let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness; + assert_eq!(regular.weight, 400); + assert_eq!(regular.italic_angle, Some(0)); + assert!(regular.panose[0] > 1, "a PANOSE family kind: {regular:?}"); + assert!(regular.x_height > 300 && regular.cap_height > regular.x_height, "{regular:?}"); + // The OS/2 average character width, in thousandths of the em. + let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSans3-Regular.ttf")).expect("bundled"); + let font = skrifa::FontRef::new(&bytes).expect("it parses"); + let (avg, em) = (font.os2().expect("an OS/2 table").x_avg_char_width(), font.head().expect("a head table").units_per_em()); + assert_eq!(f32::from(regular.avg_width), (f32::from(avg) / f32::from(em) * 1000.0).round()); + let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness; + assert!(italic.italic_angle.is_some_and(|a| a < 0), "leans right: {italic:?}"); + assert!(italic.italic && !regular.italic); + let bold = db.face("Source Sans 3", "Bold").expect("bundled").traits.likeness; + assert_eq!(bold.weight, 700); + // The OS/2 heights, in thousandths of its 1,000-unit em. + let heights = db.family_traits(HEIGHT_FAMILY).likeness; + assert_eq!((heights.x_height, heights.cap_height), (HEIGHT_X as u16, HEIGHT_CAP as u16)); + // Without them (a version 1 OS/2 table), the heights are left out. + let heightless = db.family_traits(HEIGHTLESS_FAMILY).likeness; + assert_eq!((heightless.x_height, heightless.cap_height), (0, 0), "{heightless:?}"); + assert_eq!(heightless.avg_width, regular.avg_width); +} + +/// A variable font's named instance takes its `wght` setting as its weight; the default face its +/// default weight. +#[test] +fn a_named_instance_is_weighed_by_its_axis_setting() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(variable_font().expect("the test font builds")), 3); + let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the default face").traits.likeness; + let semibold = db.face(VARIABLE_FAMILY, "SemiBold").expect("a named instance").traits.likeness; + let bold = db.face(VARIABLE_FAMILY, "Bold").expect("a named instance").traits.likeness; + assert_eq!((regular.weight, semibold.weight, bold.weight), (400, 550, 700)); + // The family is compared by its Regular face. + assert_eq!(db.family_traits(VARIABLE_FAMILY).likeness, regular); +} + +/// A face without an italic angle is compared by the other numbers only. +#[test] +fn a_missing_italic_angle_is_left_out() { + let db = db(); + let italic = db.face("Source Sans 3", "Italic").expect("bundled").traits.likeness; + assert_eq!(italic.distance(&FontLikeness { italic_angle: None, ..italic }), 0.0); + assert!(italic.distance(&FontLikeness { italic_angle: Some(0), ..italic }) > 0.0); +} + +/// A family is compared by its face nearest an upright Regular, not by the first one loaded. +#[test] +fn a_family_is_compared_by_its_regular_face() { + let db = db(); + let regular = db.face("Source Sans 3", "Regular").expect("bundled").traits.likeness; + assert_eq!(db.family_traits("Source Sans 3").likeness, regular); + assert_eq!(db.family_traits("source sans 3").likeness, regular, "by any case"); +} + +#[test] +fn likeness_is_a_distance() { + let db = db(); + let (sans, serif, mono) = + (db.family_traits("Source Sans 3").likeness, db.family_traits("Source Serif 4").likeness, db.family_traits("JetBrains Mono").likeness); + assert_eq!(sans.distance(&sans), 0.0); + assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric"); + assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0); + // A number a face does not give is left out, not counted as 0. + let unknown = FontLikeness::default(); + assert_eq!(sans.distance(&unknown), 0.0); + let lighter = FontLikeness { weight: 300, ..sans }; + assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart"); +} + +/// The family itself first, then nearest first: a copy of Source Sans 3 Regular comes before every +/// other family, and the order never moves away from the family and back. +#[test] +fn families_are_ordered_by_likeness() { + let db = db(); + let families = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]); + let order = db.similar_families("Source Sans 3", &families); + assert_eq!(order.len(), families.len()); + assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}"); + let base = db.family_traits("Source Sans 3"); + let far = |f: &str| { + let t = db.family_traits(f); + base.likeness.distance(&t.likeness) + if t.class == base.class { 0.0 } else { 2.0 } + }; + for pair in order[1..].windows(2) { + assert!(far(&pair[0]) <= far(&pair[1]), "{order:?}"); + } + // Asked by another case, or for a family not in the list. + assert_eq!(db.similar_families("SOURCE SANS 3", &families)[0], "Source Sans 3"); + let without = db.similar_families("Source Sans 3", &families[..4]); + assert_eq!(without[0], HEIGHTLESS_FAMILY); + assert!(db.similar_families("Source Sans 3", &[]).is_empty()); +} diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index d4068eb5da..9176248ffc 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -428,6 +428,29 @@ fn a_family_with_a_variable_file_beside_static_ones_is_variable() { assert!(db.family_traits(FAMILY).variable); } +/// Show Similar Fonts: the scan reads the numbers a face is compared by as loading the face does, +/// and a family's are its Regular face's whichever file is found first. +#[test] +fn the_scan_reads_a_familys_likeness_without_loading_it() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-likeness", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Sysfont-Italic.ttf"), renamed("SourceSans3-It.ttf")).unwrap(); + std::fs::write(dir.join("Sysfont-Regular.ttf"), renamed("SourceSans3-Regular.ttf")).unwrap(); + let scanned = FontDb::with_font_dirs(vec![dir.clone()]); + let likeness = scanned.family_traits(FAMILY).likeness; + assert!(!scanned.is_loaded(FAMILY), "the scan's numbers, nothing loaded"); + let loaded = FontDb::with_font_dirs(vec![]); + assert_eq!(loaded.add_font(renamed("SourceSans3-Regular.ttf")), 1); + assert_eq!(likeness, loaded.face(FAMILY, "Regular").unwrap().traits.likeness); + assert!(likeness.avg_width > 0 && likeness.x_height > 0 && likeness.italic_angle == Some(0), "{likeness:?}"); + // With only the italic loaded, the scanned Regular face still gives the family's numbers. + assert_eq!(scanned.add_font(renamed("SourceSans3-It.ttf")), 1); + assert!(scanned.is_loaded(FAMILY)); + assert_eq!(scanned.family_traits(FAMILY).likeness, likeness); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn registered_fonts_outside_the_font_folders_are_their_full_paths() { let dir = std::env::temp_dir().join("Fonts"); @@ -697,8 +720,8 @@ fn a_search_reads_at_most_its_share_of_a_font_file() { let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap(); u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap())) }; - // What one face costs: its table directory and its name and OS/2 tables. - let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2"); + // What one face costs: its table directory, its name, OS/2 and head tables and the post table's header. + let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2") + len(b"head") + 32; let n = 300; let base = 12 + 4 * n; let mut ttc = b"ttcf".to_vec(); diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 4290bc1c75..d01a8b9840 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -1,7 +1,7 @@ //! Portable 3D effect geometry: Revolve, Extrude & Bevel, Inflate and Rotate. No windowing, GPU or //! document dependencies. //! -//! Open profiles optionally close their circular ends with caps. Faces are projected and sorted back to front, +//! Open profiles optionally close their circular ends with caps, and a partial sweep its cut sides. Faces are projected and sorted back to front, //! then flat or smoothly shaded with vector gradients. This preview uses a painter's algorithm, not a depth buffer: //! intersecting profiles can have ambiguous visibility and are not solid modelling inputs. #![forbid(unsafe_code)] @@ -102,9 +102,14 @@ pub struct Revolve { pub shade: bool, /// Interpolate profile normals using vector gradients. Enabled by default. pub smooth_shading: bool, - /// Close circular endpoint rings of open profiles. Partial sweeps get sectors; - /// the angular cut sides are left open. Enabled by default. + /// Close circular endpoint rings of open profiles (sectors on a partial sweep), and the two + /// angular cut sides of a partial sweep: each is one flat face of the region between an open + /// profile and the axis, and of a closed profile's own area with its holes left open. Off, the + /// surface is hollow. Enabled by default. pub cap_ends: bool, + /// The profile's fill rule, which decides the holes the cut sides leave open in [`revolve`] and + /// [`revolve_shadowed`]. Nonzero by default. + pub fill_rule: FillRule, /// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of /// one object. `None` plans them from the profile alone. pub curve_samples: Option, @@ -140,6 +145,7 @@ impl Default for Revolve { shade: true, smooth_shading: true, cap_ends: true, + fill_rule: FillRule::NonZero, curve_samples: None, map_surface: false, } @@ -729,7 +735,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi /// Evaluate a profile in document space. All subpaths share one axis from `bounds`. /// Invalid or excessively complex inputs return an error, never a partial surface. pub fn revolve(path: &PathData, bounds: Rect, options: Revolve) -> Result, String> { - revolve_faces(path, FillRule::NonZero, bounds, options, None) + revolve_faces(path, options.fill_rule, bounds, options, None) } /// [`revolve`]'s faces as facets, back to front, for the classic surfaces: each keeps its @@ -772,7 +778,10 @@ pub fn revolve_curve_samples<'a>(paths: impl IntoIterator, if lines.saturating_add(curves.saturating_mul(MIN_CURVE_SAMPLES)) > points { return Err(TOO_COMPLEX_PROFILE.into()); } - let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)) / per_edge).min(points); + // A partial sweep with caps closes each of its two cut sides with a face for each outline, + // planned here as one for each contour. + let cut_sides = if o.cap_ends && o.angle > 0.0 && o.angle < 360.0 { contours.saturating_mul(2) } else { 0 }; + let edges = (MAX_REVOLVE_FACES.saturating_sub(caps.saturating_mul(steps)).saturating_sub(cut_sides) / per_edge).min(points); if curves == 0 { return if lines > edges { Err(TOO_COMPLEX_SURFACE.into()) } else { Ok(CURVE_SAMPLES) }; } @@ -1055,6 +1064,249 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i Ok(()) } +/// Twice the signed area of the polygon `ring`. +fn ring_area(ring: &[Point]) -> f64 { + ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum() +} + +/// The region a cut side of a partial sweep closes for one contour's profile `points`, in the +/// profile's plane and in the order the profile runs: a closed contour's own area, or an open one +/// closed along the axis at `axis` from its last end back to its first. An open contour whose ends +/// meet is taken as closed. The region is given as the loops the nonzero rule fills, so one that +/// crosses itself, such as a bow tie, gives a loop for each part it encloses. None when the contour +/// encloses no area. +fn cut_region(points: &[Point], closed: bool, axis: f64) -> Vec> { + let ring = cut_ring(points, closed, axis); + if ring.len() < 3 { + return vec![]; + } + let crossed = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&ring, true)]); + // A loop thinner than 0.000001 pt is left out, as the solids' rings leave out such debris. + match vectorcraft_pathops::try_unite_all_with(&[(&crossed, FillRule::NonZero)], 1e-6) { + Ok(loops) => loops + .subpaths + .iter() + .map(|s| s.anchors.iter().map(|a| a.p).collect::>()) + .filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10) + .collect(), + // Past the boolean's limits the region is kept as the profile draws it, as the solids' + // rings keep theirs. + Err(_) if ring_area(&ring).abs() > 1e-10 => vec![ring], + Err(_) => vec![], + } +} + +/// The ring around the region of one contour's profile `points` ([`cut_region`]), without repeated +/// points or a last point that repeats the first. +fn cut_ring(points: &[Point], closed: bool, axis: f64) -> Vec { + let (Some(&first), Some(&last)) = (points.first(), points.last()) else { return vec![] }; + let mut ring = points.to_vec(); + if !closed && first.distance(last) > 1e-10 { + ring.extend([Point::new(axis, last.y), Point::new(axis, first.y)]); + } + ring.dedup_by(|a, b| a.distance(*b) <= 1e-10); + while ring.len() > 1 && ring.first().zip(ring.last()).is_some_and(|(a, b)| a.distance(*b) <= 1e-10) { + ring.pop(); + } + ring +} + +/// The steps at whose ends the two cut sides of a partial sweep lie, each with its outward normal +/// before the view's rotation: the start faces back against the sweep, the end on along it. +fn cut_sides(at: &Sweeping) -> [(usize, V3); 2] { + // The profile lies on one side of the axis: the sweep turns it forward on the left and back on + // the right. + let side = if at.o.edge == Edge::Left { 1.0 } else { -1.0 }; + let (s, c) = at.sweep.sin_cos(); + [(0, V3(0.0, 0.0, -side)), (at.steps, V3(-s * side, 0.0, c * side))] +} + +/// Whether `p` lies inside the polygon `ring`. +fn ring_contains(ring: &[Point], p: Point) -> bool { + let mut inside = false; + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()) { + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + inside = !inside; + } + } + inside +} + +/// The regions `regions` (turned as [`oriented`] gives them) grouped into the faces of one cut +/// side: each outline, counterclockwise, first, with the holes, clockwise, that the smallest outline +/// around them holds. +fn cut_groups(regions: &[Vec]) -> Vec>> { + let bounds = |r: &[Point]| r.iter().fold(Rect::new(f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY), |b, p| b.union_pt(*p)); + // Each outline with its bounds and area, and the holes it holds. + let mut groups: Vec<(Rect, f64, Vec<&Vec>)> = + regions.iter().filter(|r| ring_area(r) > 0.0).map(|r| (bounds(r), ring_area(r), vec![r])).collect(); + for hole in regions.iter().filter(|r| ring_area(r) < 0.0) { + let Some(&p) = hole.first() else { continue }; + let owner = + groups.iter_mut().filter(|(b, _, g)| b.contains(p) && g.first().is_some_and(|o| ring_contains(o, p))).min_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((_, _, g)) = owner { + g.push(hole); + } + } + groups.into_iter().map(|(_, _, g)| g).collect() +} + +/// One face of the cut side of a partial sweep at the end of step `step`: an outline among the +/// regions ([`cut_groups`]) and its holes, turned there and drawn as one flat, evenly shaded face, +/// filled with the nonzero rule, so its holes stay open. The outline gives the face's shading, +/// depth and polygon. `None` when it is seen edge on. +fn cut_face(at: &Sweeping, regions: &[&Vec], step: usize, eye: Option, light: V3) -> Result, String> { + let origin = Point::new(at.axis, at.center_y); + let turned: Vec> = regions.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); + let Some(vertices) = turned.first() else { return Ok(None) }; + let Some(mut face) = project_face(vertices, None, at.o, origin, eye, light)? else { return Ok(None) }; + let project = |v: &V3| { + let factor = perspective_scale(eye, v.2); + Point::new(origin.x + v.0 * factor, origin.y + v.1 * factor) + }; + let drawn: Vec> = turned.iter().map(|c| c.iter().map(project).collect()).collect(); + if drawn.iter().flatten().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + return Err("Revolve projection is not finite".into()); + } + face.outline = Some(PathData::new(drawn.iter().map(|c| vectorcraft_geom::SubPath::polyline(c, true)).collect())); + Ok(Some(face)) +} + +/// Both cut sides of a partial sweep drawn, a face for each outline among `regions` with its holes +/// ([`cut_face`]), those seen edge on left out; none for no regions. +fn cut_faces(at: &Sweeping, regions: &[Vec], eye: Option, light: V3) -> Result, String> { + let groups = cut_groups(regions); + let mut out = vec![]; + for (step, _) in cut_sides(at) { + for group in &groups { + out.extend(cut_face(at, group, step, eye, light)?); + } + } + Ok(out) +} + +/// The profiles whose regions the cut sides of a partial sweep close, contour by contour, each with +/// whether its contour is closed: those of the profile drawn, and those of the profile kept for a +/// mesh. Each profile is added as its faces are swept, with any anchor [`ring_cut`] adds, so the +/// cut sides have a corner at every corner of the edges they share with the side. +struct CutRegions { + /// A partial sweep with caps: there are cut sides to close. + on: bool, + drawn: Vec<(Vec, bool)>, + kept: Vec<(Vec, bool)>, +} + +/// The loops of one contour's region turned so the region runs counterclockwise in the profile's +/// plane: filled with the nonzero rule, it fills. Its largest loop decides, and loops inside it that +/// run the other way stay holes of it. +fn outlined(mut loops: Vec>) -> Vec> { + let largest = loops.iter().map(|l| ring_area(l)).max_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or_default(); + if largest < 0.0 { + loops.iter_mut().for_each(|l| l.reverse()); + } + loops +} + +/// The regions the cut sides of a partial sweep close for the profiles `contours`, as loops that +/// the nonzero rule fills: outlines run counterclockwise in the profile's plane and holes clockwise. +/// Each open contour closes its own region ([`cut_region`]). The closed contours together close +/// what `rule` fills of them, so a contour that walls a hole leaves it open, and the parts where +/// contours overlap are filled or left open as `rule` fills them; a closed contour alone closes its +/// own region. Every corner of the closed contours' profiles on the region's edge stays a corner +/// of it. An error when the closed contours pass the limits of combining them. +fn cut_loops(contours: &[(Vec, bool)], rule: FillRule, axis: f64) -> Result>, String> { + let mut out = vec![]; + let mut rings = vec![]; + for (points, closed) in contours { + if *closed { + rings.push(points); + } else { + out.extend(outlined(cut_region(points, false, axis))); + } + } + match rings.as_slice() { + [] => {} + [one] => out.extend(outlined(cut_region(one, true, axis))), + _ => { + let subpaths = + rings.iter().map(|r| cut_ring(r, true, axis)).filter(|r| r.len() >= 3).map(|r| vectorcraft_geom::SubPath::polyline(&r, true)); + let path = PathData::new(subpaths.collect()); + let filled = vectorcraft_pathops::try_unite_all_with(&[(&path, rule)], 1e-6).map_err(|_| TOO_COMPLEX_PROFILE.to_string())?; + // The union gives outlines counterclockwise and holes clockwise. A loop thinner than + // 0.000001 pt is left out, as in [`cut_region`]. + out.extend( + filled + .subpaths + .iter() + .map(|s| s.anchors.iter().map(|a| a.p).collect::>()) + .filter(|l| l.len() >= 3 && ring_area(l).abs() > 1e-10), + ); + } + } + Ok(out) +} + +impl CutRegions { + /// The regions of a sweep with sanitized options `o`, none yet. + fn new(o: Revolve) -> Self { + Self { on: o.cap_ends && o.angle > 0.0 && o.angle < 360.0, drawn: vec![], kept: vec![] } + } + + /// Add a contour's profile `s`, drawn or kept for a mesh as `kept` says. + fn add(&mut self, s: &Swept, closed: bool, kept: bool) { + if self.on { + let to = if kept { &mut self.kept } else { &mut self.drawn }; + to.push((s.points.clone(), closed)); + } + } + + /// Close the cut sides of sweep `at` about `axis`, the holes `rule` leaves left open: keep them + /// for the mesh, if any, of `kept` (whether faces are drawn, the mesh, and the error that + /// stopped it, as [`lose_mesh`] takes them) within `face_limit` faces, and give them drawn + /// ([`cut_faces`]). + fn close( + &self, + at: &Sweeping, + (rule, axis): (FillRule, f64), + kept: (bool, &mut Option<&mut Vec>, &mut Option), + face_limit: usize, + eye: Option, + light: V3, + ) -> Result, String> { + let (draw, mesh, lost) = kept; + let result = match mesh.as_deref_mut() { + Some(m) => cut_loops(&self.kept, rule, axis).and_then(|loops| { + keep_cuts(at, &loops, |contours, normal| { + m.push((contours, normal)); + if m.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) } + }) + }), + None => Ok(()), + }; + if let Err(e) = result { + lose_mesh(draw, mesh, lost, e)?; + } + if !draw { + return Ok(vec![]); + } + cut_faces(at, &cut_loops(&self.drawn, rule, axis)?, eye, light) + } +} + +/// Keep for a mesh the two cut sides of a partial sweep: the loops `loops` of their regions +/// ([`cut_loops`]) turned to each side. Outlines run one way round and holes the other, so the mesh +/// leaves the holes open. `keep` keeps one face with its outward normal. +fn keep_cuts(at: &Sweeping, loops: &[Vec], mut keep: impl FnMut(Vec>, V3) -> Result<(), String>) -> Result<(), String> { + if loops.is_empty() { + return Ok(()); + } + for (step, normal) in cut_sides(at) { + let contours = loops.iter().map(|r| r.iter().map(|p| at.vertex(*p, step)).collect()).collect(); + keep(contours, at.o.rotate(normal))?; + } + Ok(()) +} + /// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn. fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut Option, e: String) -> Result<(), String> { if !draw { @@ -1152,6 +1404,9 @@ fn revolve_sweep( // its edges are cut into. let (mut count, mut kept_count) = (0, 0); let mut curve_budget = 0; + // With caps, a partial sweep closes its two cut sides: the regions of every contour drawn, and + // those kept for the mesh with whether each walls a hole. + let mut cuts = CutRegions::new(o); for (contour, sp) in path.subpaths.iter().enumerate() { let (mut drawn, mut kept) = (Swept::default(), Swept::default()); if let Some(first) = sp.anchors.first() { @@ -1274,6 +1529,7 @@ fn revolve_sweep( }; if let Some(m) = mesh.as_deref_mut() { let turn = prepare(&mut kept); + cuts.add(&kept, sp.closed, true); let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); if let Err(e) = kept { @@ -1284,6 +1540,7 @@ fn revolve_sweep( continue; } let turn = prepare(&mut drawn); + cuts.add(&drawn, sp.closed, false); let profile = &drawn.points; let along = along_profile(profile, axis, sp.closed); for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() { @@ -1344,6 +1601,7 @@ fn revolve_sweep( } } } + cuts.close(&at, (rule, axis), (draw, &mut mesh, &mut lost), face_limit, eye, light)?.into_iter().try_for_each(|face| emit(Some(face), 1))?; faces.sort_by(|a, b| a.depth.total_cmp(&b.depth)); Ok((faces, lost)) } diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index fc01b76785..d0ce362f1e 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -118,8 +118,9 @@ pub fn inflate_meshed( } /// Revolve's surface ([`crate::revolve`]) as a mesh. As the effect draws it, a sweep of less than -/// 360° caps its ends with sectors and leaves its two cut sides open ([`Revolve::cap_ends`]). The -/// walls of holes under `rule`, such as the counter of an O, face into the hole. +/// 360° caps its ends with sectors and closes its two cut sides with flat faces ([`Revolve::cap_ends`]). +/// The walls of holes under `rule`, such as the counter of an O, face into the hole, and the cut +/// sides leave those holes open. pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result { let mut faces = vec![]; crate::revolve_faces(path, rule, bounds, options, Some(&mut faces))?; @@ -127,7 +128,7 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo } /// The area-weighted normal of `contours` (Newell's method). -fn newell(contours: &[Vec]) -> V3 { +pub(crate) fn newell(contours: &[Vec]) -> V3 { let mut n = V3::default(); for c in contours { for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { @@ -210,7 +211,7 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> { /// The triangles covering one face: `contours` (outlines one way round, holes the other) on the /// plane across `normal` (its Newell normal). -fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result, String> { +pub(crate) fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result, String> { triangulate_keeping(contours, normal, work, false) } diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 3866565d34..a4db1d77fb 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -269,7 +269,7 @@ fn a_revolved_profile_is_a_closed_cylinder() { } #[test] -fn a_partial_revolve_caps_its_ends_with_sectors() { +fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() { let mut b = BezPath::new(); b.move_to((20.0, 0.0)); b.line_to((20.0, 100.0)); @@ -277,8 +277,12 @@ fn a_partial_revolve_caps_its_ends_with_sectors() { let r = p.bounds().unwrap(); let o = Revolve { angle: 90.0, offset: 10.0, segments: 64, ..Revolve::default() }; let m = revolve_mesh(&p, FillRule::NonZero, r, o).unwrap(); - let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0); + // The side and the two end sectors, and the two cut sides, each 10 pt from the axis by 100 pt. + let exact = 0.25 * (2.0 * std::f64::consts::PI * 10.0 * 100.0 + 2.0 * std::f64::consts::PI * 100.0) + 2.0 * 10.0 * 100.0; assert!((area(&m) - exact).abs() / exact < 0.01, "{} vs {exact}", area(&m)); + assert!(closed(&m), "the quarter of a cylinder is a closed solid"); + let hollow = revolve_mesh(&p, FillRule::NonZero, r, Revolve { cap_ends: false, ..o }).unwrap(); + assert!(!closed(&hollow)); } #[test] diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index b580ddcd5f..83c9b1dc8b 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -335,11 +335,11 @@ pub fn inflate_shadowed( } /// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces -/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where +/// [`ShadowCaster::revolve`] adds for it with the fill rule of `options`. An error where /// [`crate::revolve`] gives one. pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { let mut kept = vec![]; - let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?; + let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?; let projection = Some(crate::revolve_projection(bounds, options.sanitized())); Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) } diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index 5dba29c480..ace8566816 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -2,6 +2,7 @@ use super::*; mod caps; mod classic; +mod cut_sides; mod lighting; mod multiple_lights; mod profile_limits; diff --git a/crates/three-d/src/tests/cut_sides.rs b/crates/three-d/src/tests/cut_sides.rs new file mode 100644 index 0000000000..184ce53085 --- /dev/null +++ b/crates/three-d/src/tests/cut_sides.rs @@ -0,0 +1,297 @@ +use crate::*; +use vectorcraft_geom::Shape; + +/// Swept with Cap on, unshaded and seen from the front. +fn options() -> Revolve { + Revolve { cap_ends: true, shade: false, ..Default::default() } +} + +fn profile(data: &str) -> PathData { + PathData::from_bezpath(&BezPath::from_svg(data).unwrap()) +} + +fn area(face: &Face) -> f64 { + face.path().to_bezpath().area().abs() +} + +/// The faces of the cut sides among `faces`: the flat faces in a plane through the axis, which these +/// tests keep upright. The strips of the swept side lie off the axis, and the endpoint caps across it. +fn cut_sides(faces: &[Face]) -> Vec<&Face> { + faces.iter().filter(|f| !f.cap && f.plane.is_some_and(|p| p.offset.abs() < 1e-6 && p.normal[1].abs() < 1e-9)).collect() +} + +#[test] +fn a_half_turn_closes_both_cut_sides_with_the_region_between_the_profile_and_the_axis() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + // Seen from the front, a half turn's two cut sides both face the viewer: the profile's plane + // to the right of the axis and to its left. + let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in &cuts { + assert!((area(cut) - 40.0 * 80.0).abs() < 1e-6, "{}", area(cut)); + assert!(cut.points.iter().all(|p| (10.0 - 1e-9..=90.0 + 1e-9).contains(&p.y))); + } + assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x >= -1e-9))); + assert!(cuts.iter().any(|f| f.points.iter().all(|p| p.x <= 1e-9))); + assert!(faces.windows(2).all(|pair| pair[0].depth <= pair[1].depth)); +} + +#[test] +fn cap_off_full_turns_and_no_turn_leave_the_cut_sides_open() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + for (o, what) in [ + (Revolve { angle: 180.0, cap_ends: false, ..options() }, "hollow"), + (Revolve { angle: 360.0, rotation_x: 90.0, ..options() }, "a full turn"), + (Revolve { angle: 0.0, ..options() }, "no turn"), + ] { + let faces = revolve(&path, bounds, o).unwrap(); + assert!(cut_sides(&faces).is_empty(), "{what}"); + } +} + +#[test] +fn a_closed_profile_closes_its_cut_sides_with_its_area_and_leaves_its_hole_open() { + // A square ring away from the axis, its hole wound the other way. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L30 40 L50 40 L50 20 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() }; + let faces = revolve(&path, bounds, o).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in &cuts { + let outline = cut.outline.as_ref().unwrap(); + assert_eq!(outline.subpaths.len(), 2, "the outline and its hole"); + // Turned 20° about the vertical axis, each side is foreshortened by cos 20°. + let expected = (40.0 * 40.0 - 20.0 * 20.0) * 20f64.to_radians().cos(); + assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut)); + } + // Visibility measures the face with its hole open. + assert!(!visible_faces(&faces).unwrap().is_empty()); +} + +#[test] +fn an_even_odd_hole_wound_with_its_outline_stays_open_in_the_drawn_cut_sides() { + // The hole runs the same way round as the outline, so only the even-odd rule leaves it open. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z M30 20 L50 20 L50 40 L30 40 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, ..options() }; + let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::EvenOdd, ..o }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in cuts { + // The drawn path is filled with the nonzero rule; the hole is in the middle of the side. + let filled = cut.path().to_bezpath(); + assert!(!filled.contains(filled.bounding_box().center())); + assert!((area(cut) - (40.0 * 40.0 - 20.0 * 20.0)).abs() < 1e-6, "{}", area(cut)); + } + // Under the nonzero rule the inner contour fills too: each side is the whole outer square. + let faces = revolve(&path, bounds, Revolve { fill_rule: FillRule::NonZero, ..o }).unwrap(); + let areas: Vec = cut_sides(&faces).iter().map(|f| area(f)).collect(); + assert_eq!(areas.len(), 2); + assert!(areas.iter().all(|a| (a - 1600.0).abs() < 1e-6), "{areas:?}"); +} + +#[test] +fn a_bow_tie_whose_loops_cancel_out_closes_its_cut_sides_with_both_loops() { + // Two triangles of 400 pt² that meet at (40, 30), wound opposite ways. + let path = profile("M20 10 L60 50 L60 10 L20 50 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, rotation_y: 20.0, ..options() }; + let faces = revolve(&path, bounds, o).unwrap(); + let cuts = cut_sides(&faces); + // Each side draws each loop as a face. + assert_eq!(cuts.len(), 4); + let expected = 400.0 * 20f64.to_radians().cos(); + for cut in cuts { + assert!((area(cut) - expected).abs() < 1e-6, "{} != {expected}", area(cut)); + } + let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, rotation_y: 0.0, ..o }).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - 800.0).abs() < 1e-6, "{start}"); +} + +#[test] +fn the_mesh_closes_a_cut_side_that_crosses_itself_with_both_of_its_loops() { + // Loops of 900 pt² and 100 pt² that meet at (50, 40): the mesh covers both, and nothing + // between them. + let path = profile("M20 10 L60 50 L60 30 L20 70 Z"); + let bounds = path.bounds().unwrap(); + let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, Revolve { angle: 90.0, offset: 10.0, ..options() }).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - 1000.0).abs() < 1e-6, "{start}"); +} + +#[test] +fn a_region_thinner_than_a_millionth_of_a_point_is_debris_and_closes_no_cut_side() { + // 0.0000005 pt wide and 80 pt tall, beside a square 40 pt across. + let path = profile("M40 10 L40.0000005 10 L40.0000005 90 L40 90 Z M50 10 L90 10 L90 50 L50 50 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 90.0, offset: 10.0, ..options() }; + let mesh = revolve_mesh(&path, FillRule::NonZero, bounds, o).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - 40.0 * 40.0).abs() < 1e-6, "{start}"); +} + +#[test] +fn cut_sides_whose_holes_cannot_be_found_within_the_limit_are_refused() { + // 2,100 squares on top of each other: each test of a point meets every square. + let square = "M20 10 L60 10 L60 50 L20 50 Z "; + let path = profile(&square.repeat(2100)); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 90.0, offset: 10.0, ..options() }; + assert_eq!(revolve(&path, bounds, o).err().as_deref(), Some(TOO_COMPLEX_PROFILE)); + // Hollow, the sweep has no cut sides to close. + assert!(revolve(&path, bounds, Revolve { cap_ends: false, ..o }).is_ok()); +} + +#[test] +fn visibility_keeps_both_of_two_separate_regions_wound_opposite_ways() { + let path = profile("M20 10 L30 10 L30 50 L20 50 Z M40 10 L40 50 L50 50 L50 10 Z"); + let bounds = path.bounds().unwrap(); + // Seen from behind, the half turn's walls are behind both cut sides, which nothing covers. Seen + // from the front, the walls the outer square sweeps cover both sides completely. + for (rotation_y, all) in [(180.0, 4.0 * 10.0 * 40.0), (0.0, 0.0)] { + let faces = revolve(&path, bounds, Revolve { angle: 180.0, offset: 10.0, rotation_y, ..options() }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 4, "a face for each region on each side"); + let mut depths: Vec = cuts.iter().map(|f| f.depth).collect(); + depths.dedup(); + let visible = visible_faces(&faces).unwrap(); + let shown: f64 = visible + .iter() + .filter(|v| depths.contains(&v.depth)) + .flat_map(|v| v.path.subpaths.iter().map(|s| PathData::new(vec![s.clone()]).to_bezpath().area().abs())) + .sum(); + assert!((shown - all).abs() < 1e-6, "turned {rotation_y}°, the cut sides show {shown}, not {all}"); + } +} + +#[test] +fn every_open_contour_of_a_compound_profile_closes_its_own_region_on_each_side() { + let path = profile("M40 10 L40 40 M20 60 L50 90"); + let bounds = Rect::new(0.0, 10.0, 50.0, 90.0); + let faces = revolve(&path, bounds, Revolve { angle: 180.0, ..options() }).unwrap(); + let mut areas: Vec = cut_sides(&faces).iter().map(|f| area(f)).collect(); + areas.sort_by(f64::total_cmp); + // The trapezoid between the slanted line and the axis, (20 + 50) / 2 × 30, and 40 × 30. + let expected = [35.0 * 30.0, 35.0 * 30.0, 40.0 * 30.0, 40.0 * 30.0]; + assert_eq!(areas.len(), 4); + assert!(areas.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-6), "{areas:?}"); +} + +#[test] +fn a_cut_side_seen_edge_on_is_not_drawn() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + // A quarter turn ends in the plane through the axis toward the viewer. + let faces = revolve(&path, bounds, Revolve { angle: 90.0, ..options() }).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 1); + assert!((area(cuts[0]) - 40.0 * 80.0).abs() < 1e-6); +} + +#[test] +fn cut_sides_are_shaded_evenly_by_their_plane() { + let path = profile("M40 10 L40 90"); + let bounds = Rect::new(0.0, 10.0, 40.0, 90.0); + let o = Revolve { angle: 180.0, shade: true, rotation_y: 30.0, ..options() }; + let faces = revolve(&path, bounds, o).unwrap(); + let cuts = cut_sides(&faces); + assert_eq!(cuts.len(), 2); + for cut in cuts { + assert!(cut.gradient.is_none(), "a flat face is shaded evenly"); + assert!(cut.plane.is_some()); + assert!((0.0..=1.0).contains(&cut.brightness)); + // Both sides lie in the plane through the axis turned 30°, whose normal faces the viewer. + let n = cut.normal; + assert!((n[0].abs() - 30f64.to_radians().sin()).abs() < 1e-9 && n[2] > 0.0, "{n:?}"); + } +} + +/// The area of the triangles of `mesh` whose normal is `normal`. +fn area_facing(mesh: &Mesh, normal: [f64; 3]) -> f64 { + mesh.triangles + .iter() + .filter(|t| t.iter().all(|&i| mesh.normals[i as usize].iter().zip(normal).all(|(a, b)| (a - b).abs() < 1e-9))) + .map(|t| { + let [a, b, c] = t.map(|i| mesh.positions[i as usize]); + let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]); + let x = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + (x[0] * x[0] + x[1] * x[1] + x[2] * x[2]).sqrt() / 2.0 + }) + .sum() +} + +#[test] +fn the_mesh_closes_both_cut_sides_and_leaves_holes_open_under_either_fill_rule() { + let ring = "M20 10 L60 10 L60 50 L20 50 Z"; + let o = Revolve { angle: 90.0, offset: 10.0, ..options() }; + let expected = 40.0 * 40.0 - 20.0 * 20.0; + // The hole wound against the outline, and wound with it under even-odd. + for (hole, rule) in [("M30 20 L30 40 L50 40 L50 20 Z", FillRule::NonZero), ("M30 20 L50 20 L50 40 L30 40 Z", FillRule::EvenOdd)] { + let path = profile(&format!("{ring} {hole}")); + let mesh = revolve_mesh(&path, rule, path.bounds().unwrap(), o).unwrap(); + // The start faces back, against the sweep; a quarter turn ends facing left, along it. + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + let end = area_facing(&mesh, [-1.0, 0.0, 0.0]); + assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}"); + assert!((end - expected).abs() < 1e-6, "{rule:?}: {end}"); + } + let path = profile(ring); + let hollow = revolve_mesh(&path, FillRule::NonZero, path.bounds().unwrap(), Revolve { cap_ends: false, ..o }).unwrap(); + assert_eq!(area_facing(&hollow, [0.0, 0.0, -1.0]), 0.0); +} + +#[test] +fn overlapping_contours_close_the_cut_sides_with_what_the_fill_rule_fills() { + // Two squares of 1,600 pt² that overlap in 300 pt², and only one corner of each lies inside + // the other. The even-odd rule leaves the overlap open; the nonzero rule fills it once. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z M50 20 L90 20 L90 60 L50 60 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 180.0, offset: 10.0, ..options() }; + for (rule, expected) in [(FillRule::EvenOdd, 2.0 * (1600.0 - 300.0)), (FillRule::NonZero, 2.0 * 1600.0 - 300.0)] { + let faces = revolve(&path, bounds, Revolve { fill_rule: rule, ..o }).unwrap(); + let cuts = cut_sides(&faces); + let total: f64 = cuts.iter().map(|f| area(f)).sum(); + assert!((total - 2.0 * expected).abs() < 1e-6, "{rule:?}: both sides cover {total}, not twice {expected}"); + let mesh = revolve_mesh(&path, rule, bounds, Revolve { angle: 90.0, ..o }).unwrap(); + let start = area_facing(&mesh, [0.0, 0.0, -1.0]); + assert!((start - expected).abs() < 1e-6, "{rule:?}: {start}"); + } +} + +#[test] +fn the_cut_sides_kept_for_a_mesh_have_a_corner_at_every_corner_of_the_side() { + // With graphics mapped, the square's side is cut half way round from its outer side, at + // (20, 30), which is not an anchor: the cut side takes that corner too. + let path = profile("M20 10 L60 10 L60 50 L20 50 Z"); + let bounds = path.bounds().unwrap(); + let o = Revolve { angle: 90.0, offset: 10.0, map_surface: true, ..options() }; + let mut faces = vec![]; + revolve_faces(&path, FillRule::NonZero, bounds, o, Some(&mut faces)).unwrap(); + // The corners in the plane where the sweep starts, of every face kept for the mesh and of the + // cut side's alone, which faces back against the sweep. + let in_plane = |all: bool| { + let start = |n: &V3| (n.0.abs() + n.1.abs() + (n.2 + 1.0).abs()) < 1e-9; + let kept = faces.iter().filter(|(_, n)| all || start(n)); + kept.flat_map(|(contours, _)| contours.iter().flatten().copied()).filter(|v| v.2.abs() < 1e-9).collect::>() + }; + let cut = in_plane(false); + assert!(!cut.is_empty()); + for p in in_plane(true) { + assert!(cut.iter().any(|q| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9), "{p:?} is not a corner of the cut side"); + } +} + +#[test] +fn the_mesh_cut_sides_face_out_of_a_sweep_on_the_left_of_its_axis() { + // The axis is 40 pt to the right of the line, which sweeps from the left of the axis to its back. + let path = profile("M40 10 L40 90"); + let o = Revolve { angle: 90.0, edge: Edge::Right, offset: 40.0, ..options() }; + let mesh = revolve_mesh(&path, FillRule::NonZero, Rect::new(40.0, 10.0, 40.0, 90.0), o).unwrap(); + assert!((area_facing(&mesh, [0.0, 0.0, 1.0]) - 40.0 * 80.0).abs() < 1e-6); + assert!((area_facing(&mesh, [1.0, 0.0, 0.0]) - 40.0 * 80.0).abs() < 1e-6); +} diff --git a/crates/three-d/src/visibility.rs b/crates/three-d/src/visibility.rs index 3ed491ae10..71c5af62c3 100644 --- a/crates/three-d/src/visibility.rs +++ b/crates/three-d/src/visibility.rs @@ -199,7 +199,8 @@ pub fn visible_faces(faces: &[Face]) -> Result, String> { }) { return Err("Revolve visibility requires finite projected faces".into()); } - let all = faces.iter().flat_map(|f| &f.points).copied().collect::>(); + let outlines = faces.iter().filter_map(|f| f.outline.as_ref()).flat_map(|o| o.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p))); + let all = faces.iter().flat_map(|f| f.points.iter().copied()).chain(outlines).collect::>(); let total = bounds(&all); if total.width() <= 0.0 || total.height() <= 0.0 { return Ok(vec![]); @@ -222,7 +223,9 @@ pub fn visible_faces(faces: &[Face]) -> Result, String> { if pieces.is_empty() { continue; } - let source_bounds = bounds(&face.points); + // A face drawn as several contours, such as a cut side of a partial sweep, reaches past its + // own polygon: look for covers over all of its pieces. + let source_bounds = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)).unwrap_or_else(|| bounds(&face.points)); let mut fragments: Vec<_> = pieces.iter().map(|p| p.points.clone()).collect(); let mut clipped = false; 'covers: for tile in index.tiles(source_bounds) { diff --git a/crates/three-d/src/visibility_parts.rs b/crates/three-d/src/visibility_parts.rs index 2a14435025..ebf1d47b4b 100644 --- a/crates/three-d/src/visibility_parts.rs +++ b/crates/three-d/src/visibility_parts.rs @@ -91,6 +91,22 @@ fn triangulate(mut points: Vec, epsilon: f64, work: &mut usize, depth: us Ok(out) } +/// Triangles covering a flat face drawn as several straight-edged contours, such as a cut side of a +/// partial Revolve whose profile has holes: outlines one way round and holes the other, the holes +/// left uncovered. The work is checked before the face is cut, at four times its corners squared. +fn with_holes(outline: &vectorcraft_geom::PathData, epsilon: f64, work: &mut usize) -> Result>, String> { + const LIMIT: &str = "Revolve visibility exceeds its geometry work limit"; + let rings: Vec> = outline.subpaths.iter().map(|s| s.anchors.iter().map(|a| crate::V3(a.p.x, a.p.y, 0.0)).collect()).collect(); + let corners: usize = rings.iter().map(Vec::len).sum(); + *work = work.saturating_add(corners.saturating_mul(corners).saturating_mul(4)); + if *work > MAX_WORK { + return Err(LIMIT.into()); + } + let mut spent = 0; + let triangles = crate::mesh::triangulate(&rings, crate::mesh::newell(&rings), &mut spent)?; + Ok(triangles.into_iter().map(|t| clean(t.iter().map(|v| Point::new(v.0, v.1)).collect(), epsilon)).filter(|t| !t.is_empty()).collect()) +} + pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result>, String> { if let Some(strips) = &face.visibility_pieces { let mut out = vec![]; @@ -99,6 +115,9 @@ pub(super) fn pieces(face: &Face, epsilon: f64, work: &mut usize) -> Result 1) { + return with_holes(outline, epsilon, work); + } if !face.cap { return triangulate(clean(face.points.clone(), epsilon), epsilon, work, 0); } diff --git a/crates/tools/src/addons/trim.rs b/crates/tools/src/addons/trim.rs index 9eee5c436f..9c0681f4b4 100644 --- a/crates/tools/src/addons/trim.rs +++ b/crates/tools/src/addons/trim.rs @@ -3,10 +3,20 @@ //! rectangle and removes every stretch it touches; an Alt-drag draws a freehand line and removes //! every stretch it crosses. Each runs `addon.pathtools.trim` on release, as one undo step, on //! every path that can be edited, selected or not. Escape during a drag removes nothing. +//! +//! Hovering shows in red the stretch a click would remove while finding its crossings takes at +//! most a twentieth of the work a click may do ([`HOVER`]), and a drag shows what it would remove while +//! it reaches few paths ([`PREVIEW`]). + +pub mod plan; use serde_json::json; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{BezPath, PathData, Point, Rect}; +use vectorcraft_pathops::addons::pathtools as pt; +use self::plan::{Limits, Pick, Stretches}; +use crate::builder::HIGHLIGHT_RED; use crate::draw2::FEEDBACK; use crate::xform::polygon; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -21,6 +31,18 @@ const MIN_DRAG_PX: f64 = 3.0; pub(crate) const MAX_POINTS: usize = 65_536; /// The command the tool runs. const COMMAND: &str = "addon.pathtools.trim"; +/// How much finding the crossings for a preview may take: a twentieth of what the command may. +const PREVIEW_CROSSINGS: pt::Work = pt::Work::share(20); +/// How much hovering may work out on each move: past it the hover shows no highlight, and a +/// click still removes the stretch. +pub const HOVER: Limits = Limits { crossings: PREVIEW_CROSSINGS, ..Limits::COMMAND }; +/// How much a drag's preview may work out on each move: past it the drag shows no preview, and +/// the release still removes everything it reaches. +pub const PREVIEW: Limits = Limits { paths: 32, box_tests: 10_000_000, line_tests: 1_000_000, crossings: PREVIEW_CROSSINGS }; +/// The most points a freehand line has for the drag to show a preview. +const PREVIEW_POINTS: usize = 4_096; +/// The preview's line width (screen pixels). +const PREVIEW_PX: f32 = 3.0; #[derive(Default)] pub struct TrimTool { @@ -32,6 +54,27 @@ pub struct TrimTool { freehand: bool, /// The pointer went `MIN_DRAG_PX` or more from the press: the gesture is a drag from then on. moved: bool, + /// The stretches the gesture would remove, and the document state they were found in. + preview: Vec, + preview_state: Option, + /// Finding the drag's crossings took more work than a preview may: it shows none until the + /// next press. + gave_up: bool, + /// The stretches of the paths looked at so far, for the document state `seen`. + stretches: Stretches, + seen: Option, +} + +/// The document's revision and its isolated object: what a pick is worked out for. +type State = ((u64, u64), Option); + +fn state(cx: &ToolContext) -> State { + (cx.revision, cx.isolation) +} + +/// How near the pointer a click finds a path (pt). +fn reach(cx: &ToolContext) -> f64 { + cx.tol(REACH).min(100.0) } impl TrimTool { @@ -40,6 +83,64 @@ impl TrimTool { self.line.clear(); self.freehand = false; self.moved = false; + self.gave_up = false; + self.preview.clear(); + } + + /// Work out what `pick` would remove, within `limits`, as the preview: nothing when it + /// removes nothing or needs more work than that (then why). + fn look(&mut self, cx: &ToolContext, pick: &Pick, limits: Limits) -> Option { + if self.seen != Some(state(cx)) { + self.stretches.clear(); + self.seen = Some(state(cx)); + } + let root = crate::ordinary_isolation(cx.doc, cx.isolation); + self.preview_state = Some(state(cx)); + match plan::plan(cx.doc, root, pick, limits, &mut self.stretches) { + Ok(all) => { + self.preview = all.into_iter().flat_map(|t| t.removed).map(|sp| PathData::single(sp).to_bezpath()).collect(); + None + } + Err(e) => { + self.preview.clear(); + Some(e) + } + } + } + + /// The preview of the drag as it is: its rectangle, or its freehand line to `to`. + fn look_at_drag(&mut self, cx: &ToolContext, to: Point) { + let Some(start) = self.start else { return }; + if self.gave_up { + self.preview.clear(); + return; + } + if !self.freehand { + self.look_or_give_up(cx, &Pick::Rect(Rect::from_points(start, to))); + return; + } + if self.line.len() > PREVIEW_POINTS { + self.preview.clear(); + return; + } + let mut pts = self.line.clone(); + if pts.last().is_some_and(|p| *p != to) { + pts.push(to); + } + if pts.len() < 2 { + self.preview.clear(); + return; + } + let bounds = pts.iter().fold(Rect::from_points(to, to), |r, q| r.union_pt(*q)); + self.look_or_give_up(cx, &Pick::Line(pts, bounds)); + } + + /// [`Self::look`] for a drag. A drag that reaches too many paths may come back to fewer; one + /// whose crossings or line take too much work shows nothing more. + fn look_or_give_up(&mut self, cx: &ToolContext, pick: &Pick) { + if let Some(plan::TooMuch::Crossings | plan::TooMuch::Line) = self.look(cx, pick, PREVIEW) { + self.gave_up = true; + } } } @@ -57,15 +158,22 @@ impl Tool for TrimTool { if ev.kind == PointerKind::Up { self.reset(); } + self.preview.clear(); return vec![]; } match ev.kind { + PointerKind::Move => { + self.look(cx, &Pick::At(ev.pos, reach(cx)), HOVER); + vec![] + } PointerKind::Down => { self.start = Some(ev.pos); self.end = ev.pos; self.freehand = ev.mods.alt; self.moved = false; self.line = if self.freehand { vec![ev.pos] } else { vec![] }; + // Until the pointer moves away, the press is a click at this point. + self.look(cx, &Pick::At(ev.pos, reach(cx)), HOVER); vec![] } PointerKind::Drag if self.start.is_some() => { @@ -79,6 +187,9 @@ impl Tool for TrimTool { } self.line.push(ev.pos); } + if self.moved { + self.look_at_drag(cx, ev.pos); + } vec![] } PointerKind::Up => { @@ -89,7 +200,7 @@ impl Tool for TrimTool { // A press that stayed near where it started is a click, even when a freehand line // took a few points on the way. One that went farther stays a drag when it comes back. if !moved && start.distance(ev.pos) < cx.tol(MIN_DRAG_PX) { - return vec![Action::Exec(COMMAND.into(), json!({"at": [start.x, start.y], "tolerance": cx.tol(REACH).min(100.0)}))]; + return vec![Action::Exec(COMMAND.into(), json!({"at": [start.x, start.y], "tolerance": reach(cx)}))]; } if !freehand { let r = Rect::from_points(start, ev.pos); @@ -116,16 +227,34 @@ impl Tool for TrimTool { self.start.is_some() && key == ToolKey::Escape } - fn overlays(&self, _cx: &ToolContext) -> Vec { - let Some(start) = self.start else { return vec![] }; - if self.freehand { - return if self.line.len() < 2 { - vec![] - } else { - vec![Overlay::Path { path: polygon(&self.line, false), color: FEEDBACK, width: 1.0, dashed: false }] - }; + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.start.is_none() { + self.preview.clear(); } - if self.moved { vec![Overlay::Marquee(Rect::from_points(start, self.end))] } else { vec![] } + } + + /// The highlight shows what lies under the pointer, which panning or an edit changes. + fn wants_rehover(&self) -> bool { + true + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + // A preview found in another revision of the document, or for another isolated object, is + // out of date. + let mut out: Vec = if self.preview_state == Some(state(cx)) { + self.preview.iter().map(|p| Overlay::Path { path: p.clone(), color: HIGHLIGHT_RED, width: PREVIEW_PX, dashed: false }).collect() + } else { + vec![] + }; + let Some(start) = self.start else { return out }; + if self.freehand { + if self.line.len() >= 2 { + out.push(Overlay::Path { path: polygon(&self.line, false), color: FEEDBACK, width: 1.0, dashed: false }); + } + } else if self.moved { + out.push(Overlay::Marquee(Rect::from_points(start, self.end))); + } + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { @@ -137,7 +266,9 @@ impl Tool for TrimTool { mod tests { use super::*; use crate::testutil::*; - use vectorcraft_doc::Selection; + use vectorcraft_doc::{Appearance, Document, Node, Selection}; + use vectorcraft_geom::kurbo::{ParamCurve, PathSeg}; + use vectorcraft_geom::shapes; fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { PointerEvent::new(kind, x, y) @@ -151,7 +282,8 @@ mod tests { cx.zoom = 2.0; let mut t = TrimTool::default(); assert!(t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0)).is_empty()); - assert!(t.busy() && t.overlays(&cx).is_empty()); + // No marquee for a press; the rectangle, which nothing crosses, would go whole. + assert!(t.busy() && matches!(t.overlays(&cx).as_slice(), [Overlay::Path { color: HIGHLIGHT_RED, .. }])); let up = t.pointer(&cx, &ev(PointerKind::Up, 100.5, 100.0)); assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [100.0, 100.0], "tolerance": 2.0}))], "4 px at 200%"); assert!(!t.busy()); @@ -166,7 +298,10 @@ mod tests { let mut t = TrimTool::default(); t.pointer(&cx, &ev(PointerKind::Down, 160.0, 130.0)); assert!(t.pointer(&cx, &ev(PointerKind::Drag, 140.0, 90.0)).is_empty(), "nothing runs while dragging"); - assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(r)] if *r == Rect::new(140.0, 90.0, 160.0, 130.0))); + assert!(matches!( + t.overlays(&cx).as_slice(), + [Overlay::Path { color: HIGHLIGHT_RED, .. }, Overlay::Marquee(r)] if *r == Rect::new(140.0, 90.0, 160.0, 130.0) + )); let up = t.pointer(&cx, &ev(PointerKind::Up, 140.0, 90.0)); assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"rect": [140.0, 90.0, 20.0, 40.0]}))]); // Escape during a drag: nothing runs on release, and the key is the tool's only then. @@ -233,4 +368,247 @@ mod tests { assert!(!t.busy()); assert!(t.pointer(&cx, &ev(PointerKind::Up, 0.0, 0.0)).is_empty()); } + + /// A document holding `paths`, bottom to top. + fn doc_of(paths: Vec) -> (Document, Vec) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for (i, p) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, p, Appearance::default_art())).unwrap(); + ids.push(id); + } + (d, ids) + } + + fn open(pts: &[(f64, f64)]) -> PathData { + let mut b = BezPath::new(); + for (i, (x, y)) in pts.iter().enumerate() { + if i == 0 { b.move_to((*x, *y)) } else { b.line_to((*x, *y)) } + } + PathData::from_bezpath(&b) + } + + /// The red stretches shown, each as its two ends. + fn shown(t: &TrimTool, cx: &ToolContext) -> Vec<(Point, Point)> { + t.overlays(cx) + .iter() + .filter_map(|o| match o { + Overlay::Path { path, color, .. } if *color == HIGHLIGHT_RED => { + let segs: Vec = path.segments().collect(); + Some((segs.first()?.start(), segs.last()?.end())) + } + _ => None, + }) + .collect() + } + + fn hover(t: &mut TrimTool, cx: &ToolContext, x: f64, y: f64) -> Vec<(Point, Point)> { + assert!(t.pointer(cx, &ev(PointerKind::Move, x, y)).is_empty(), "hovering runs nothing"); + shown(t, cx) + } + + /// The two ends, either way round, are near (ax, ay) and (bx, by). + fn ends_are(e: (Point, Point), (ax, ay): (f64, f64), (bx, by): (f64, f64)) -> bool { + let near = |p: Point, x: f64, y: f64| p.distance(Point::new(x, y)) < 1e-3; + (near(e.0, ax, ay) && near(e.1, bx, by)) || (near(e.0, bx, by) && near(e.1, ax, ay)) + } + + /// What a click at (x, y) with the tool's reach removes, worked out as the command does. + fn click_removes(d: &Document, cx: &ToolContext, x: f64, y: f64) -> Vec { + let all = plan::plan(d, None, &Pick::At(Point::new(x, y), reach(cx)), Limits::COMMAND, &mut Stretches::default()).unwrap(); + all.into_iter().flat_map(|t| t.removed).map(|sp| PathData::single(sp).to_bezpath()).collect() + } + + fn red_paths(t: &TrimTool, cx: &ToolContext) -> Vec { + t.overlays(cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { path, color, .. } if color == HIGHLIGHT_RED => Some(path), + _ => None, + }) + .collect() + } + + #[test] + fn hovering_shows_the_stretch_a_click_removes_on_a_line_across_an_ellipse() { + let ellipse = shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 200.0)); + let (d, _) = doc_of(vec![ellipse, open(&[(50.0, 150.0), (350.0, 150.0)])]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + // The ellipse's upper half, between the two places the line crosses it. + let top = hover(&mut t, &cx, 200.0, 101.0); + assert!(matches!(top.as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))), "{top:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 200.0, 101.0)); + // The line's end outside the ellipse, and its middle inside it. + let end = hover(&mut t, &cx, 70.0, 150.0); + assert!(matches!(end.as_slice(), [e] if ends_are(*e, (50.0, 150.0), (100.0, 150.0))), "{end:?}"); + let middle = hover(&mut t, &cx, 200.0, 151.0); + assert!(matches!(middle.as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0))), "{middle:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 200.0, 151.0)); + // Off every path: no highlight. + assert!(hover(&mut t, &cx, 400.0, 400.0).is_empty()); + assert!(t.overlays(&cx).is_empty()); + } + + #[test] + fn hovering_an_open_square_and_a_path_that_crosses_itself() { + // Three sides of a square, crossed by an upright through the top and bottom sides. + let square = open(&[(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)]); + let (d, _) = doc_of(vec![square, open(&[(150.0, 50.0), (150.0, 250.0)])]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + let side = hover(&mut t, &cx, 201.0, 150.0); + assert!(matches!(side.as_slice(), [e] if ends_are(*e, (150.0, 100.0), (150.0, 200.0))), "{side:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 201.0, 150.0)); + let corner = hover(&mut t, &cx, 110.0, 99.0); + assert!(matches!(corner.as_slice(), [e] if ends_are(*e, (100.0, 100.0), (150.0, 100.0))), "{corner:?}"); + + // A Z drawn back over itself: its first and last sides cross at (50, 50). + let (d, _) = doc_of(vec![open(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)])]); + let cx = crate::testutil::cx(&d, &sel, &p); + let mut t = TrimTool::default(); + let lobe = hover(&mut t, &cx, 101.0, 50.0); + assert!(matches!(lobe.as_slice(), [e] if ends_are(*e, (50.0, 50.0), (50.0, 50.0))), "{lobe:?}"); + assert_eq!(red_paths(&t, &cx), click_removes(&d, &cx, 101.0, 50.0)); + let tail = hover(&mut t, &cx, 10.0, 11.0); + assert!(matches!(tail.as_slice(), [e] if ends_are(*e, (0.0, 0.0), (50.0, 50.0))), "{tail:?}"); + } + + #[test] + fn hidden_and_locked_paths_show_nothing_and_a_changed_document_drops_the_highlight() { + let (mut d, ids) = doc_of(vec![open(&[(0.0, 100.0), (300.0, 100.0)]), open(&[(0.0, 200.0), (300.0, 200.0)])]); + d.node_mut(ids[0]).unwrap().visible = false; + d.node_mut(ids[1]).unwrap().locked = true; + let (sel, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + assert!(hover(&mut t, &cx, 150.0, 100.0).is_empty(), "hidden"); + assert!(hover(&mut t, &cx, 150.0, 200.0).is_empty(), "locked"); + + let (d, _) = doc_of(vec![open(&[(0.0, 100.0), (300.0, 100.0)])]); + cx.doc = &d; + assert_eq!(hover(&mut t, &cx, 150.0, 100.0).len(), 1); + // Once the document changes, the highlight found before is not shown. + cx.revision = (0, 1); + assert!(shown(&t, &cx).is_empty()); + // Leaving the canvas clears it. + cx.revision = (0, 0); + t.hover_ended(&cx); + assert!(shown(&t, &cx).is_empty()); + } + + #[test] + fn in_isolation_mode_only_paths_inside_the_isolated_group_are_highlighted() { + // A group holding a line across, and an upright outside it that crosses the line. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let across = Node::path(d.alloc_id(), open(&[(0.0, 100.0), (300.0, 100.0)]), Appearance::default_art()); + let group = Node::group(d.alloc_id(), vec![std::sync::Arc::new(across)]); + let g = group.id; + d.insert(Some(l), 0, group).unwrap(); + let upright = d.alloc_id(); + d.insert(Some(l), 1, Node::path(upright, open(&[(150.0, 0.0), (150.0, 300.0)]), Appearance::default_art())).unwrap(); + let (sel, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + // Outside isolation mode the upright is highlighted; entering it drops that highlight. + assert_eq!(hover(&mut t, &cx, 151.0, 50.0).len(), 1); + cx.isolation = Some(g); + assert!(shown(&t, &cx).is_empty(), "found before the group was isolated"); + // The upright is not trimmed, and still crosses the line inside the group. + assert!(hover(&mut t, &cx, 151.0, 50.0).is_empty()); + let left = hover(&mut t, &cx, 50.0, 101.0); + assert!(matches!(left.as_slice(), [e] if ends_are(*e, (0.0, 100.0), (150.0, 100.0))), "{left:?}"); + } + + #[test] + fn a_path_whose_crossings_take_more_than_a_hover_may_shows_nothing_and_a_click_still_trims_it() { + // 2,500 segments crossing each other's boxes: about 3,125,000 pairs, more than a twentieth + // of the 60,000,000 a click may look at. + let row = open(&(0..=2500).map(|i| (i as f64 * 0.1, 100.0)).collect::>()); + let (d, _) = doc_of(vec![row]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + assert!(hover(&mut t, &cx, 125.0, 100.0).is_empty()); + assert_eq!(click_removes(&d, &cx, 125.0, 100.0).len(), 1); + let up = { + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, 125.0, 100.0)) + }; + assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [125.0, 100.0], "tolerance": 4.0}))]); + } + + #[test] + fn a_small_drag_shows_what_it_would_remove_and_a_large_one_shows_nothing() { + let ellipse = shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 200.0)); + let (d, _) = doc_of(vec![ellipse, open(&[(50.0, 150.0), (350.0, 150.0)])]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + // A rectangle across the ellipse's top: its upper half. + t.pointer(&cx, &ev(PointerKind::Down, 190.0, 90.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 210.0, 110.0)); + assert!(matches!(shown(&t, &cx).as_slice(), [e] if ends_are(*e, (100.0, 150.0), (300.0, 150.0)))); + t.pointer(&cx, &ev(PointerKind::Up, 210.0, 110.0)); + assert!(shown(&t, &cx).is_empty(), "the release drops the preview"); + // An Alt line through the ellipse's left side and the line's left end. + let alt = Mods { alt: true, ..Mods::default() }; + t.pointer(&cx, &ev(PointerKind::Down, 60.0, 140.0).with_mods(alt)); + t.pointer(&cx, &ev(PointerKind::Drag, 110.0, 160.0)); + assert_eq!(shown(&t, &cx).len(), 2, "the line's end and the ellipse's lower half"); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(shown(&t, &cx).is_empty()); + + // A rectangle over more paths than the preview's limit shows nothing. + let many: Vec = (0..=PREVIEW.paths).map(|i| open(&[(0.0, i as f64 * 2.0), (100.0, i as f64 * 2.0)])).collect(); + let (d, _) = doc_of(many); + let cx = crate::testutil::cx(&d, &sel, &p); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, -10.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 60.0, 500.0)); + assert!(shown(&t, &cx).is_empty()); + assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(_)])); + // What lies under a still pointer changes when the view pans: the canvas hovers again. + assert!(t.wants_rehover()); + } + + #[test] + fn crossings_kept_from_earlier_picks_still_count_against_the_budget() { + // Three rows of 7,000 segments, apart: each costs 24,500,000 pairs of the 60,000,000 a + // pick may look at, so a rectangle over all three is refused. + let row = |y: f64| open(&(0..=7000).map(|i| (i as f64 * 0.01, y)).collect::>()); + let (d, _) = doc_of(vec![row(0.0), row(10.0), row(20.0)]); + let rect = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 21.0)); + assert_eq!(plan::plan(&d, None, &rect, Limits::COMMAND, &mut Stretches::default()), Err(plan::TooMuch::Crossings)); + // Hovering two of them keeps their crossings; the rectangle is refused all the same. + let mut kept = Stretches::default(); + for y in [0.0, 10.0] { + assert_eq!(plan::plan(&d, None, &Pick::At(Point::new(35.0, y), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1)); + } + assert_eq!(plan::plan(&d, None, &rect, Limits::COMMAND, &mut kept), Err(plan::TooMuch::Crossings)); + // A rectangle over two is not. + let two = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 11.0)); + assert_eq!(plan::plan(&d, None, &two, Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(2)); + + // A drag whose crossings take too much shows nothing until the next press, even over less. + // Rows of 1,500 segments cost 1,125,000 pairs each, so a preview has room for two. + let row = |y: f64| open(&(0..=1500).map(|i| (i as f64 * 0.05, y)).collect::>()); + let (d, _) = doc_of(vec![row(0.0), row(10.0), row(20.0)]); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TrimTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, -1.0, -1.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 21.0)); + assert!(shown(&t, &cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 5.0)); + assert!(shown(&t, &cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, 80.0, 5.0)); + t.pointer(&cx, &ev(PointerKind::Down, -1.0, -1.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 80.0, 5.0)); + assert_eq!(shown(&t, &cx).len(), 1); + } } diff --git a/crates/tools/src/addons/trim/plan.rs b/crates/tools/src/addons/trim/plan.rs new file mode 100644 index 0000000000..d88dbec7b8 --- /dev/null +++ b/crates/tools/src/addons/trim/plan.rs @@ -0,0 +1,351 @@ +//! What Trim at Crossings removes: the stretch at a point, every stretch a rectangle touches, or +//! every stretch a line through some points crosses, on every path that can be edited. The command +//! `addon.pathtools.trim` applies it, and the tool shows it before a click or while a drag stays +//! small, so the two always agree. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_doc::{Document, NodeId, NodeKind}; +use vectorcraft_geom::kurbo::{Line, PathSeg}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit}; +use vectorcraft_pathops::addons::pathtools as pt; + +/// What picks the stretches to remove. +#[derive(Clone, Debug, PartialEq)] +pub enum Pick { + /// The stretch of the nearest path within the tolerance (pt) of the point. + At(Point, f64), + /// Every stretch the rectangle touches. + Rect(Rect), + /// Every stretch the line through the points crosses, with the points' bounds. + Line(Vec, Rect), +} + +/// Why a pick could not be worked out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TooMuch { + /// Finding where the paths cross took more than its budget. + Crossings, + /// The line has too many pieces, or passes too many segments, to check. + Line, + /// The rectangle or line reaches more paths than the limit. + Paths, +} + +impl TooMuch { + /// The error message the command reports. + pub fn message(self) -> &'static str { + match self { + TooMuch::Crossings => "the paths are too many or too tangled to find where they cross", + TooMuch::Line => "the line is too long, or the paths it passes too many, to check", + TooMuch::Paths => "the rectangle or line reaches too many paths to check", + } + } +} + +/// How much work one pick may take. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Most paths a rectangle or a line may reach. + pub paths: usize, + /// Most box tests between the paths to trim and the other paths. + pub box_tests: usize, + /// Most box tests between a line's pieces and the paths' segments. + pub line_tests: usize, + /// The crossing work of every path the pick trims together. + pub crossings: pt::Work, +} + +impl Limits { + /// The command's limits. + pub const COMMAND: Limits = Limits { paths: usize::MAX, box_tests: 50_000_000, line_tests: 60_000_000, crossings: pt::Work::share(1) }; +} + +/// One path the pick trims. +#[derive(Clone, Debug, PartialEq)] +pub struct Trimmed { + pub id: NodeId, + /// What takes its place: a path per piece for a path of one subpath, one path holding the + /// pieces for a path of more, nothing when no piece is left. + pub pieces: Vec, + /// The stretches removed, each an open subpath. + pub removed: Vec, + /// How many stretches were removed. + pub count: usize, +} + +/// The stretches of each subpath of a path between the places it is crossed, for the document as +/// it was when they were found, with the crossing work finding them took. A pick fills it with the +/// paths it looks at; one kept between picks on an unchanged document saves finding the same +/// crossings again, and a pick still draws their work from its budget, so it fails where a pick +/// without them would. It also keeps the paths whose crossings could not be found within the whole +/// crossing work of the picks' limits (`whole`), which no pick with those limits can find either. +#[derive(Default)] +pub struct Stretches { + by_path: HashMap>, pt::Work)>, + too_much: HashSet, + whole: Option, +} + +impl Stretches { + pub fn clear(&mut self) { + self.by_path.clear(); + self.too_much.clear(); + self.whole = None; + } +} + +/// A path that takes part: its id, geometry and control-point box. +type Part<'a> = (NodeId, &'a PathData, Rect); + +/// The paths that take part, bottom to top: the ones that can be edited, without guides and +/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the +/// members of a compound clipping path included. +fn parts(d: &Document) -> Vec> { + let editable = d.editable(); + let mut masks = HashSet::new(); + d.walk(|n| { + if n.clips() + && let Some(first) = n.children().and_then(|c| c.first()) + { + first.walk(&mut |m| { + masks.insert(m.id); + }); + } + }); + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind + && !masks.contains(&n.id) + && let Some(b) = path.control_bounds() + && editable(n.id) + { + out.push((n.id, path, b)); + } + }); + out +} + +/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`; +/// `None` once it is spent. +fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option { + let segs: Vec<_> = (0..sp.segment_count()) + .map(|i| { + let c = sp.segment(i); + (c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9)) + }) + .collect(); + let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) }; + for w in pts.windows(2) { + let [a, b] = w else { continue }; + let piece = Rect::from_points(*a, *b); + *budget = budget.checked_sub(1)?; + if !reach.overlaps(piece) { + continue; + } + for (c, r) in &segs { + *budget = budget.checked_sub(1)?; + if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() { + return Some(true); + } + } + } + Some(false) +} + +/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`. +fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result { + match pick { + Pick::At(..) => Ok(false), + Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)), + Pick::Line(pts, _) => crossed_by_line(piece, pts, budget).ok_or(TooMuch::Line), + } +} + +/// What a trim leaves of a path: its subpaths, the stretches removed and how many. +type Cut = (Vec, Vec, usize); + +/// What trimming `path` by `pick` leaves (`on`: the place of `Pick::At` on it): its subpaths then, +/// the stretches removed and how many. `None` when none goes. A rectangle or a line that touches +/// no part of `path` leaves it out before its crossings are looked for. +#[allow(clippy::too_many_arguments)] +fn trimmed<'a>( + id: NodeId, + path: &PathData, + others: &dyn Fn() -> Vec<&'a PathData>, + pick: &Pick, + on: Option, + budget: &mut usize, + work: &mut pt::Work, + stretches: &mut Stretches, +) -> Result, TooMuch> { + let reached = match pick { + Pick::At(..) => true, + Pick::Rect(r) => hit::intersects_rect(path, *r), + Pick::Line(..) => { + let mut any = false; + for sp in &path.subpaths { + if touches(sp, pick, budget)? { + any = true; + break; + } + } + any + } + }; + if !reached { + return Ok(None); + } + let all = match stretches.by_path.get(&id) { + Some((all, cost)) => { + work.draw(*cost).ok_or(TooMuch::Crossings)?; + all.clone() + } + None if stretches.too_much.contains(&id) => return Err(TooMuch::Crossings), + None => { + let before = *work; + let Some(places) = pt::crossings_on_within(path, &others(), work) else { + if Some(before) == stretches.whole { + stretches.too_much.insert(id); + } + return Err(TooMuch::Crossings); + }; + let all: Vec> = path + .subpaths + .iter() + .enumerate() + .map(|(si, sp)| { + // The places come in subpath order: this subpath's are one run of them. + let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si); + let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect(); + pt::spans(sp, &here) + }) + .collect(); + stretches.by_path.insert(id, (all.clone(), work.spent_since(before))); + all + } + }; + let mut subs = vec![]; + let mut removed = vec![]; + let mut count = 0; + for ((si, sp), spans) in path.subpaths.iter().enumerate().zip(&all) { + let marks: Vec = match pick { + Pick::At(..) => { + let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, spans, seg, t)); + (0..spans.len()).map(|i| Some(i) == at).collect() + } + _ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::>()?, + }; + match pt::without_spans(sp, spans, &marks) { + Some(pieces) => { + count += marks.iter().filter(|m| **m).count(); + removed.extend(spans.iter().zip(&marks).filter(|(_, m)| **m).map(|(s, _)| pt::slice(sp, *s)).filter(|p| p.anchors.len() >= 2)); + subs.extend(pieces); + } + None => subs.push(sp.clone()), + } + } + Ok((count > 0).then_some((subs, removed, count))) +} + +/// What `pick` removes from the document's paths, bottom to top. With `isolation` (the isolated +/// object in isolation mode, see [`crate::ordinary_isolation`]) only paths inside it are trimmed; +/// paths outside it still cross them. `stretches` must hold only what it learned from this +/// document as it is. +pub fn plan(d: &Document, isolation: Option, pick: &Pick, limits: Limits, stretches: &mut Stretches) -> Result, TooMuch> { + let parts = parts(d); + let in_scope = |id: NodeId| isolation.is_none_or(|r| id == r || d.ancestry(id).is_some_and(|a| a.contains(&r))); + // The paths to trim, each with the place `at` falls on. + let targets: Vec<(usize, Option)> = match pick { + Pick::At(at, tolerance) => { + let mut best: Option<(usize, pt::Place, f64)> = None; + for (i, (id, path, b)) in parts.iter().enumerate() { + if !in_scope(*id) { + continue; + } + let b = b.inflate(*tolerance, *tolerance); + if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) { + continue; + } + // Of paths equally near, the one on top. + if let Some((si, seg, t, _, dist)) = path.nearest(*at) + && dist <= *tolerance + && best.is_none_or(|b| dist <= b.2) + { + best = Some((i, (si, seg, t), dist)); + } + } + best.map(|(i, on, _)| (i, Some(on))).into_iter().collect() + } + Pick::Rect(r) | Pick::Line(_, r) => { + parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect() + } + }; + // Each path to trim has its box tested against every other path's. + if targets.len() > limits.paths || targets.len().saturating_mul(parts.len()) > limits.box_tests { + return Err(TooMuch::Paths); + } + let mut out = vec![]; + let mut budget = limits.line_tests; + // A path that failed within a whole budget of another size may fit in this one. + if stretches.whole != Some(limits.crossings) { + stretches.too_much.clear(); + stretches.whole = Some(limits.crossings); + } + // One budget of crossing work for every path the pick trims. + let mut work = limits.crossings; + for (i, on) in targets { + let Some((id, path, b)) = parts.get(i) else { continue }; + let reach = b.inflate(1e-3, 1e-3); + let others = || parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect(); + let Some((subs, removed, count)) = trimmed(*id, path, &others, pick, on, &mut budget, &mut work, stretches)? else { continue }; + // A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths. + let pieces = match (path.subpaths.len(), subs.is_empty()) { + (_, true) => vec![], + (1, false) => subs.into_iter().map(PathData::single).collect(), + _ => vec![PathData::new(subs)], + }; + out.push(Trimmed { id: *id, pieces, removed, count }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{Appearance, Node}; + + fn row(y: f64, segments: usize) -> PathData { + PathData::single(SubPath::polyline(&(0..=segments).map(|i| Point::new(i as f64 * 0.01, y)).collect::>(), false)) + } + + #[test] + fn a_path_too_large_for_a_whole_budget_is_not_searched_again_and_one_cut_short_by_a_shared_budget_is() { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for (i, p) in [row(0.0, 7000), row(10.0, 7000), row(20.0, 7000), row(30.0, 10_001)].into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, p, Appearance::default_art())).unwrap(); + ids.push(id); + } + let mut kept = Stretches::default(); + // More segments than a crossing search takes: no budget finds its crossings. + assert_eq!(plan(&d, None, &Pick::At(Point::new(50.0, 30.0), 1.0), Limits::COMMAND, &mut kept), Err(TooMuch::Crossings)); + assert!(kept.too_much.contains(&ids[3])); + // The third of three rows runs out of the budget the rectangle shares; alone it has enough. + let rect = Pick::Rect(Rect::new(-1.0, -1.0, 80.0, 21.0)); + assert_eq!(plan(&d, None, &rect, Limits::COMMAND, &mut kept), Err(TooMuch::Crossings)); + assert!(!kept.too_much.contains(&ids[2])); + assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 20.0), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1)); + // A row is too much for a twentieth of the budget, and is remembered only for picks with it. + let small = Limits { crossings: pt::Work::share(20), ..Limits::COMMAND }; + let mut kept = Stretches::default(); + assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 10.0), 1.0), small, &mut kept), Err(TooMuch::Crossings)); + assert!(kept.too_much.contains(&ids[1])); + assert_eq!(plan(&d, None, &Pick::At(Point::new(35.0, 10.0), 1.0), Limits::COMMAND, &mut kept).map(|t| t.len()), Ok(1)); + assert!(!kept.too_much.contains(&ids[1])); + kept.clear(); + assert!(kept.too_much.is_empty() && kept.by_path.is_empty()); + } +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1e8f57ffc9..0e7280ae9a 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -164,6 +164,17 @@ pub enum PixelOp { Scaling, } +/// The isolated group, layer or object in isolation mode, of `isolation` (the document's isolated +/// node). Pattern editing mode, opacity mask editing and symbol editing mode isolate their own +/// layer, which does not count here; an object isolated inside them counts. +pub fn ordinary_isolation(doc: &Document, isolation: Option) -> Option { + isolation.filter(|l| { + !doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) + && !doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) + && !doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) + }) +} + /// Read-only context a tool sees. pub struct ToolContext<'a> { pub doc: &'a Document, diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 0245f75112..13691da613 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -2,10 +2,12 @@ //! its artboard (the whole image when it lies inside one); its handles and its inside drag it, //! always within the image, and the part outside it is dimmed. Enter (or the Control bar's Apply) //! crops the image to it (`object.cropImage {rect}`), Escape (or Cancel) leaves it as it was; both -//! go back to the Selection tool. The Control bar edits the box through the `rect` option. +//! go back to the Selection tool. The Control bar edits the box through the `rect` option, the +//! point its X and Y name through `reference`, whether its W and H keep their proportions through +//! `linked`, and the cropped image's resolution through `ppi`. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; +use vectorcraft_doc::{Document, ImageObject, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle}; @@ -18,6 +20,97 @@ pub const ID: &str = "cropImage"; /// The smallest the box gets, in points. const MIN: f64 = 1.0; +/// The resolutions the Control bar's PPI list offers; those above the image's own are disabled. +pub const PPI_CHOICES: [f64; 5] = [72.0, 96.0, 150.0, 200.0, 300.0]; + +/// The highest resolution a linked image can be cropped to. +pub const LINKED_MAX_PPI: f64 = 300.0; + +/// The reference point the box's X and Y name by default: its center (of the nine points of +/// [`vectorcraft_geom::reference_point`], left to right and top to bottom). +pub const CENTER: usize = 4; + +/// An image's own resolution in pixels per inch (along its denser side, measured on its pixel +/// grid, so turning it changes nothing), and the highest resolution it can be cropped to: its own, +/// or [`LINKED_MAX_PPI`] for a linked image. +pub fn image_ppi(im: &ImageObject) -> (f64, f64) { + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + // The document lengths of one pixel's sides. + let (sx, sy) = (a.hypot(b), c.hypot(d)); + let own = 72.0 / sx.min(sy).max(1e-9); + (own, if im.link.is_some() { LINKED_MAX_PPI } else { own }) +} + +/// Whether cropping `im` at `ppi` keeps its pixels as they are: its pixels are square (the same +/// resolution across and down) and at that resolution, within `tolerance` ppi. +pub fn keeps_resolution(im: &ImageObject, ppi: f64, tolerance: f64) -> bool { + let [a, b, c, d, _, _] = im.xf.as_coeffs(); + let (x, y) = (72.0 / a.hypot(b).max(1e-9), 72.0 / c.hypot(d).max(1e-9)); + (x - ppi).abs() <= tolerance && (y - ppi).abs() <= tolerance +} + +/// Checks the values `tool.setOption` gives the tool before any is set: `ppi` a number from 1 to +/// 2400, and no more than `max` (the selected image's limit, from [`image_ppi`]), or null; +/// `reference` a whole number from 0 to 8; `linked` true or false. +pub fn check_options(values: &serde_json::Map, max: Option) -> Result<(), String> { + for (key, v) in values { + let error = match key.as_str() { + "ppi" if v.is_null() => None, + "ppi" => match v.as_f64().filter(|n| (1.0..=2400.0).contains(n)) { + None => Some(format!("`ppi` must be a number from 1 to 2400 or null, not {v}")), + Some(n) => { + max.filter(|m| n > m + 1e-6).map(|m| format!("`ppi` can't be more than {} for this image", (m * 100.0 + 1e-6).floor() / 100.0)) + } + }, + "reference" => (!v.as_u64().is_some_and(|n| n <= 8)).then(|| format!("`reference` must be a whole number from 0 to 8, not {v}")), + "linked" => (!v.is_boolean()).then(|| format!("`linked` must be true or false, not {v}")), + _ => None, + }; + if let Some(e) = error { + return Err(e); + } + } + Ok(()) +} + +/// The box `r` over an image with bounds `image`, with one Control bar field set: `x` or `y` moves +/// the box so its `reference` point is there; `width` or `height` resizes it about that point, the +/// other side following in proportion when `linked`. Sizes below [`MIN`] are raised to it, a +/// linked size with both sides together so it keeps its proportions. A +/// linked size is held to the image with both sides scaled together, and a box that fits is slid +/// back within the image, so its proportions survive being kept within it. `None` for another key +/// or a value that isn't finite. +pub fn edited_box(r: Rect, image: Rect, reference: usize, linked: bool, key: &str, v: f64) -> Option { + if !v.is_finite() { + return None; + } + let p = vectorcraft_geom::reference_point(r, reference); + let (mut w, mut h) = (r.width(), r.height()); + let fit = |b: Rect| if b.width() <= image.width() + 1e-9 && b.height() <= image.height() + 1e-9 { slid_within(b, image) } else { b }; + match key { + "x" => return Some(fit(r + Vec2::new(v - p.x, 0.0))), + "y" => return Some(fit(r + Vec2::new(0.0, v - p.y))), + // Linked, both sides take one scale, raised so neither side falls below MIN. + "width" | "height" if linked && w > 0.0 && h > 0.0 => { + let k = (v / if key == "width" { w } else { h }).max(MIN / w).max(MIN / h); + (w, h) = (w * k, h * k); + } + "width" => w = v.max(MIN), + "height" => h = v.max(MIN), + _ => return None, + } + if linked { + let k = (image.width() / w).min(image.height() / h).min(1.0); + if k.is_finite() && k > 0.0 { + (w, h) = (w * k, h * k); + } + } + // The reference point keeps its place: it sits at the same fraction of the new box. + let (fx, fy) = ((reference % 3) as f64 / 2.0, (reference / 3).min(2) as f64 / 2.0); + let (x0, y0) = (p.x - w * fx, p.y - h * fy); + Some(fit(Rect::new(x0, y0, x0 + w, y0 + h))) +} + /// Create the Crop Image tool by id (None = not ours). pub fn create(id: &str) -> Option> { (id == ID).then(|| Box::new(CropImageTool::default()) as Box) @@ -75,7 +168,6 @@ enum Drag { Move(Point, Rect), } -#[derive(Default)] pub struct CropImageTool { /// The box, for the image it was made for (None: set from outside, for the selected image); /// None until it's dragged or set. @@ -83,6 +175,18 @@ pub struct CropImageTool { drag: Option, /// Where the pointer last was on the canvas (measurement label during a drag). last: Point, + /// The cropped image's resolution in pixels per inch (None: the image's own). + ppi: Option, + /// The point of the box the Control bar's X and Y name (0..=8, [`CENTER`] by default). + reference: usize, + /// Whether the Control bar's W and H keep the box's proportions. + linked: bool, +} + +impl Default for CropImageTool { + fn default() -> Self { + Self { rect: None, drag: None, last: Point::ZERO, ppi: None, reference: CENTER, linked: false } + } } impl CropImageTool { @@ -93,24 +197,49 @@ impl CropImageTool { crop_box(cx.doc, cx.selection, set) } - /// Crop to the box and go back to the Selection tool (only back when it covers the image). + /// Crop to the box at the chosen resolution and go back to the Selection tool (only back when + /// the box covers the image and the resolution is the image's own). The box and the resolution + /// are forgotten when the tool is left, so a crop that fails keeps them for another try. fn apply(&mut self, cx: &ToolContext) -> Vec { let current = self.current(cx); - self.reset(); + let ppi = self.ppi; + self.drag = None; let mut out = vec![]; - if let Some((_, image, r)) = current - && !same(r, image) - { - out.push(Action::Exec("object.cropImage".into(), json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }))); + if let Some((id, image, r)) = current { + let im = match cx.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Image(im)) => Some(&**im), + _ => None, + }; + let max = im.map_or(f64::INFINITY, |im| image_ppi(im).1); + // A resolution set before this image was selected is held to this image's limit. + let resample = ppi.map(|v| v.min(max)).filter(|v| im.is_none_or(|im| !keeps_resolution(im, *v, 1e-3))); + // A turned or skewed image is drawn to be cropped: the resolution goes with it even when + // it is the image's own, which the PPI field shows until another is chosen (when it is + // one `object.cropImage` takes). A resolution chosen for it crops even over the whole box. + let drawn = im.filter(|im| { + let [_, b, c, _, _, _] = im.xf.as_coeffs(); + b.abs() > 1e-9 || c.abs() > 1e-9 + }); + let own = |im: &ImageObject| Some(image_ppi(im).0).filter(|v| (1.0..=2400.0).contains(v) && *v <= max + 1e-6); + let send = resample.or_else(|| drawn.and_then(|im| ppi.map(|v| v.min(max)).or_else(|| own(im)))); + if !same(r, image) || resample.is_some() || (drawn.is_some() && ppi.is_some()) { + let mut p = json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }); + if let Some(v) = send { + p["ppi"] = json!(v); + } + out.push(Action::Exec("object.cropImage".into(), p)); + } } out.push(Action::SwitchTool("selection".into())); out } + /// Forget the box and the resolution; the reference point and the link stay as they were set. fn reset(&mut self) { self.rect = None; self.drag = None; self.last = Point::ZERO; + self.ppi = None; } } @@ -242,19 +371,40 @@ impl Tool for CropImageTool { } /// `rect`: the box as `[x, y, width, height]` once it's been dragged or set (until then it's - /// [`initial_box`]). + /// [`initial_box`]); `ppi` once it's been set (until then the image's own); `reference` (0..=8) + /// and `linked`. fn options(&self) -> Value { - match self.rect { - Some((_, r)) => json!({ "rect": [r.x0, r.y0, r.width(), r.height()] }), - None => json!({}), + let mut o = json!({ "reference": self.reference, "linked": self.linked }); + if let Some((_, r)) = self.rect { + o["rect"] = json!([r.x0, r.y0, r.width(), r.height()]); } + if let Some(v) = self.ppi { + o["ppi"] = json!(v); + } + o } /// `rect` `[x, y, width, height]` sets the box (kept within the selected image when used); - /// anything else puts it back where it starts. + /// anything else puts it back where it starts. `ppi` a positive number sets the cropped + /// image's resolution (null: the image's own). `reference` a whole number 0..=8 sets the point X and Y name, and `linked` + /// true or false the link of W and H. `tool.setOption` refuses other values of those three + /// ([`check_options`]); one that reaches the tool anyway puts that setting back to its default. fn set_option(&mut self, key: &str, value: &Value) { - if key != "rect" { - return; + match key { + "ppi" => { + self.ppi = value.as_f64().filter(|v| v.is_finite() && *v > 0.0); + return; + } + "reference" => { + self.reference = value.as_u64().filter(|v| *v <= 8).map_or(CENTER, |v| v as usize); + return; + } + "linked" => { + self.linked = value.as_bool().unwrap_or(false); + return; + } + "rect" => {} + _ => return, } // Invalid components must discard the whole box, not silently shift the // coordinates by dropping a non-numeric entry. @@ -310,6 +460,15 @@ mod tests { } } + /// Enter, then the switch to the Selection tool that a crop that ran is followed by. + fn enter(t: &mut CropImageTool, cx: &ToolContext) -> Vec { + let acts = t.key(cx, ToolKey::Enter, Mods::default()); + if acts.contains(&Action::SwitchTool("selection".into())) { + assert!(t.deactivate(cx).is_empty()); + } + acts + } + fn crop_rect(acts: &[Action]) -> Option> { acts.iter().find_map(|a| match a { Action::Exec(c, v) if c == "object.cropImage" => Some(v["rect"].as_array()?.iter().filter_map(Value::as_f64).collect()), @@ -341,11 +500,11 @@ mod tests { assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Highlight { .. })).count(), 2, "above and right of the box"); assert_eq!(ov.iter().filter(|o| matches!(o, Overlay::Handle { .. })).count(), 8); // Enter crops to it and goes back to the Selection tool. - let acts = t.key(&cx, ToolKey::Enter, Mods::default()); + let acts = enter(&mut t, &cx); assert_eq!(crop_rect(&acts), Some(vec![50.0, 70.0, 130.0, 90.0])); assert_eq!(acts.last(), Some(&Action::SwitchTool("selection".into()))); assert!(t.options().get("rect").is_none(), "the next crop starts afresh"); - assert!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())).is_none(), "the whole image: nothing to cut"); + assert!(crop_rect(&enter(&mut t, &cx)).is_none(), "the whole image: nothing to cut"); } /// In a view turned 90° the handles' cursors turn with the view. @@ -369,10 +528,10 @@ mod tests { let mut t = CropImageTool::default(); drag(&mut t, &cx, (100.0, 150.0), (110.0, 150.0)); assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]); - assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![0.0, 100.0, 150.0, 100.0])); + assert_eq!(crop_rect(&enter(&mut t, &cx)), Some(vec![0.0, 100.0, 150.0, 100.0])); // The Control bar sets the box; it stays within the image. t.set_option("rect", &json!([100, 120, 500, 20])); - assert_eq!(crop_rect(&t.key(&cx, ToolKey::Enter, Mods::default())), Some(vec![100.0, 120.0, 50.0, 20.0])); + assert_eq!(crop_rect(&enter(&mut t, &cx)), Some(vec![100.0, 120.0, 50.0, 20.0])); // Nothing selected: no box, and the keys go elsewhere. let none = Selection::default(); let cx = crate::testutil::cx(&d, &none, &p); @@ -411,6 +570,196 @@ mod tests { assert_eq!(tool.options()["rect"], json!([10.0, 20.0, 30.0, 40.0])); } + /// The Control bar's fields: X and Y place the reference point, W and H resize about it, and + /// the link keeps the proportions. + #[test] + fn fields_move_and_resize_the_box_about_its_reference_point() { + let r = Rect::new(10.0, 20.0, 110.0, 70.0); + let big = Rect::new(0.0, 0.0, 1000.0, 1000.0); + // The center (the default): today's behavior. + assert_eq!(edited_box(r, big, CENTER, false, "x", 100.0), Some(Rect::new(50.0, 20.0, 150.0, 70.0))); + assert_eq!(edited_box(r, big, CENTER, false, "width", 50.0), Some(Rect::new(35.0, 20.0, 85.0, 70.0))); + // The top-left corner: X and Y name it, and a new size keeps it where it is. + assert_eq!(edited_box(r, big, 0, false, "x", 0.0), Some(Rect::new(0.0, 20.0, 100.0, 70.0))); + assert_eq!(edited_box(r, big, 0, false, "y", 5.0), Some(Rect::new(10.0, 5.0, 110.0, 55.0))); + assert_eq!(edited_box(r, big, 0, false, "height", 10.0), Some(Rect::new(10.0, 20.0, 110.0, 30.0))); + // The bottom-right corner keeps its place too. + assert_eq!(edited_box(r, big, 8, false, "width", 40.0), Some(Rect::new(70.0, 20.0, 110.0, 70.0))); + // Linked: the other side follows in proportion (100 × 50 → 40 × 20, then 60 × 30). + assert_eq!(edited_box(r, big, 0, true, "width", 40.0), Some(Rect::new(10.0, 20.0, 50.0, 40.0))); + assert_eq!(edited_box(r, big, 8, true, "height", 30.0), Some(Rect::new(50.0, 40.0, 110.0, 70.0))); + // A size below a point is raised to one; other keys and values that aren't finite change nothing. + assert_eq!(edited_box(r, big, 0, false, "width", -5.0), Some(Rect::new(10.0, 20.0, 11.0, 70.0))); + assert_eq!(edited_box(r, big, 0, false, "angle", 5.0), None); + assert_eq!(edited_box(r, big, 0, false, "x", f64::NAN), None); + // Within a 120 × 80 image: a linked size is held to the image with both sides scaled + // (200 × 100 → 120 × 60), and the box slides back within it, keeping its 2:1 proportions. + let image = Rect::new(0.0, 0.0, 120.0, 80.0); + assert_eq!(edited_box(r, image, 0, true, "width", 200.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0))); + assert_eq!(edited_box(r, image, 0, true, "height", 70.0), Some(Rect::new(0.0, 20.0, 120.0, 80.0))); + // A move past the edge slides the box back without changing its size. + assert_eq!(edited_box(r, image, 0, false, "x", 50.0), Some(Rect::new(20.0, 20.0, 120.0, 70.0))); + // Unlinked, a side larger than the image is left for the box's own limit to cut. + assert_eq!(edited_box(r, image, 0, false, "width", 200.0), Some(Rect::new(10.0, 20.0, 210.0, 70.0))); + } + + #[test] + fn reference_link_and_resolution_are_tool_options() { + let mut t = CropImageTool::default(); + assert_eq!(t.options(), json!({ "reference": 4, "linked": false })); + t.set_option("reference", &json!(0)); + t.set_option("linked", &json!(true)); + t.set_option("ppi", &json!(150)); + assert_eq!(t.options(), json!({ "reference": 0, "linked": true, "ppi": 150.0 })); + // Values that don't read put each back to its default. + for (k, v) in [("reference", json!(9)), ("linked", json!("yes")), ("ppi", json!(0)), ("ppi", json!(-72)), ("ppi", json!("high"))] { + t.set_option(k, &v); + } + assert_eq!(t.options(), json!({ "reference": 4, "linked": false })); + } + + #[test] + fn option_values_are_checked_before_they_are_set() { + let values = |v: Value| v.as_object().cloned().unwrap(); + assert_eq!(check_options(&values(json!({ "ppi": 150.5, "reference": 8, "linked": true, "rect": [0, 0, 1, 1] })), None), Ok(())); + assert_eq!(check_options(&values(json!({ "ppi": null })), Some(36.0)), Ok(())); + assert_eq!(check_options(&values(json!({ "ppi": 36 })), Some(36.0)), Ok(())); + for (v, want) in [ + (json!({ "ppi": 0.5 }), "`ppi` must be a number from 1 to 2400 or null, not 0.5"), + (json!({ "ppi": 2401 }), "`ppi` must be a number from 1 to 2400 or null, not 2401"), + (json!({ "ppi": "high" }), "`ppi` must be a number from 1 to 2400 or null, not \"high\""), + (json!({ "ppi": 72 }), "`ppi` can't be more than 36 for this image"), + (json!({ "reference": 9 }), "`reference` must be a whole number from 0 to 8, not 9"), + (json!({ "reference": 1.5 }), "`reference` must be a whole number from 0 to 8, not 1.5"), + (json!({ "linked": "yes" }), "`linked` must be true or false, not \"yes\""), + ] { + assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); + } + } + + /// An image's own resolution, and the most it can be cropped to. + #[test] + fn image_resolution_and_its_limit() { + let (d, s) = doc_with_image((50.0, 60.0)); + let (id, _) = selected_image(&d, &s).unwrap(); + let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") }; + // 100 px over 200 pt: half a pixel per point, 36 ppi. + assert_eq!(image_ppi(&im), (36.0, 36.0)); + // Turned, it is the same image: 36 ppi, not the density across its bounding box. + let turned = ImageObject { xf: Affine::rotate(0.5) * im.xf, ..(*im).clone() }; + assert!((image_ppi(&turned).0 - 36.0).abs() < 1e-9); + // Stretched to 3 pt a pixel across, its denser side counts. + let stretched = ImageObject { xf: Affine::scale_non_uniform(3.0, 2.0), ..(*im).clone() }; + assert_eq!(image_ppi(&stretched).0, 36.0); + // Its own resolution keeps its pixels; pixels that are not square are resampled at any resolution. + assert!(keeps_resolution(&im, 36.0, 1e-6) && !keeps_resolution(&im, 18.0, 1e-6)); + assert!(!keeps_resolution(&stretched, 36.0, 1e-6) && !keeps_resolution(&stretched, 24.0, 1e-6)); + let linked = ImageObject { link: Some("photo.png".into()), ..*im }; + assert_eq!(image_ppi(&linked), (36.0, LINKED_MAX_PPI)); + } + + /// Apply sends the chosen resolution with the box, even for a box over the whole image; the + /// image's own resolution sends nothing new, and one above the image's limit is held to it. + #[test] + fn apply_sends_the_chosen_resolution() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let cx = cx(&d, &s, &p); + let exec = |acts: &[Action]| { + acts.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "object.cropImage" => Some(v.clone()), + _ => None, + }) + }; + let mut t = CropImageTool::default(); + t.set_option("ppi", &json!(20)); + assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [50.0, 60.0, 200.0, 100.0], "ppi": 20.0 }))); + assert!(t.options().get("ppi").is_none(), "the next crop starts at the image's own"); + t.set_option("ppi", &json!(36)); + assert_eq!(exec(&enter(&mut t, &cx)), None, "the image's own over the whole image: nothing to do"); + t.set_option("ppi", &json!(36)); + t.set_option("rect", &json!([60, 70, 100, 50])); + assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + // A resolution set before this image was selected is held to its limit: 300 → its own 36. + t.set_option("ppi", &json!(300)); + t.set_option("rect", &json!([60, 70, 100, 50])); + assert_eq!(exec(&enter(&mut t, &cx)), Some(json!({ "rect": [60.0, 70.0, 100.0, 50.0] }))); + t.set_option("ppi", &json!(300)); + assert_eq!(exec(&enter(&mut t, &cx)), None, "held to its own over the whole image: nothing to do"); + } + + /// A turned image is drawn to be cropped, so Apply sends its own resolution too, the one the + /// PPI field shows, or the one chosen. + #[test] + fn apply_sends_a_turned_image_s_own_resolution() { + // Turned about the page's corner, it stays within the artboard. + let (mut d, s) = doc_with_image((150.0, 60.0)); + let Some(id) = s.objects.first().copied() else { panic!("an image") }; + if let Some(NodeKind::Image(im)) = d.node_mut(id).map(|n| &mut n.kind) { + im.xf = Affine::rotate(0.5) * im.xf; + } + let p = paint(); + let cx = cx(&d, &s, &p); + let ppi = |acts: &[Action]| { + acts.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "object.cropImage" => v.get("ppi").and_then(Value::as_f64), + _ => None, + }) + }; + let mut t = CropImageTool::default(); + t.set_option("rect", &json!([150, 150, 20, 20])); + assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); + t.set_option("rect", &json!([150, 150, 20, 20])); + t.set_option("ppi", &json!(36)); + assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); + // Over the whole box, Apply crops at a resolution chosen, and leaves it alone without one. + t.set_option("ppi", &json!(36)); + assert!(ppi(&enter(&mut t, &cx)).is_some_and(|v| (v - 36.0).abs() < 1e-9)); + assert!(!enter(&mut t, &cx).iter().any(|a| matches!(a, Action::Exec(..)))); + // A linked image's own resolution above what it can be cropped to is not sent in its place. + let Some(NodeKind::Image(im)) = d.node(id).map(|n| n.kind.clone()) else { panic!("an image") }; + let mut linked = d.clone(); + if let Some(NodeKind::Image(l)) = linked.node_mut(id).map(|n| &mut n.kind) { + l.link = Some("photo.png".into()); + l.xf = im.xf * Affine::scale(0.1); + } + // 0.2 pt a pixel: 360 ppi, above the 300 a linked image is cropped to. + let cx = crate::testutil::cx(&linked, &s, &p); + t.set_option("rect", &json!([105, 128, 4, 4])); + assert_eq!(ppi(&enter(&mut t, &cx)), None); + } + + /// A crop that fails leaves the tool chosen (the switch to the Selection tool is not made), so + /// the box and the resolution stay for another try; leaving the tool forgets them. + #[test] + fn the_box_and_resolution_stay_until_the_tool_is_left() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = CropImageTool::default(); + t.set_option("ppi", &json!(20)); + t.set_option("rect", &json!([60, 70, 100, 50])); + let acts = t.key(&cx, ToolKey::Enter, Mods::default()); + assert_eq!(crop_rect(&acts), Some(vec![60.0, 70.0, 100.0, 50.0])); + assert_eq!(t.options()["rect"], json!([60.0, 70.0, 100.0, 50.0])); + assert_eq!(t.options()["ppi"], json!(20.0)); + assert!(t.deactivate(&cx).is_empty()); + assert!(t.options().get("rect").is_none() && t.options().get("ppi").is_none()); + } + + /// A linked size raised to the smallest box keeps the box's proportions: both sides grow + /// together until the shorter one is a point. + #[test] + fn a_linked_size_at_the_smallest_keeps_its_proportions() { + let big = Rect::new(0.0, 0.0, 1000.0, 1000.0); + let wide = Rect::new(10.0, 20.0, 110.0, 70.0); + assert_eq!(edited_box(wide, big, 0, true, "width", 1.0), Some(Rect::new(10.0, 20.0, 12.0, 21.0))); + assert_eq!(edited_box(wide, big, 0, true, "height", 0.25), Some(Rect::new(10.0, 20.0, 12.0, 21.0))); + let tall = Rect::new(10.0, 20.0, 60.0, 120.0); + assert_eq!(edited_box(tall, big, 0, true, "height", 1.0), Some(Rect::new(10.0, 20.0, 11.0, 22.0))); + assert_eq!(edited_box(tall, big, 0, true, "width", -3.0), Some(Rect::new(10.0, 20.0, 11.0, 22.0))); + } + #[test] fn the_tool_is_made_by_its_id() { assert_eq!(crate::create(ID).id(), ID); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 89250fa0fb..502fd16dbd 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -18,7 +18,8 @@ //! gives there. The other tools //! collect the drag polyline (shown as an overlay) and run one command on release. With Shift //! held, the Blob Brush's points stay on the horizontal or -//! vertical line through the press point. Alt held at the press, or before the Blob Brush's drag +//! vertical line through the press point, and the Eraser's on the line from the press point at the +//! nearest 45° step from the Constrain Angle. Alt held at the press, or before the Blob Brush's drag //! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths. //! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke //! begins closes the path on release. @@ -29,9 +30,11 @@ //! line to 45° steps from the canvas axes. mod area; +mod line; use std::cell::Cell; use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::{Calligraphic, Variation}; @@ -43,6 +46,7 @@ use super::{FEEDBACK, blob_area, blob_tip, eraser_tip, points_json, polyline}; use crate::guides::DrawSnap; use crate::{Action, Cursor, Mods, Overlay, PenPose, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use area::{AreaKey, AreaPreview}; +use line::LinePreview; /// How far from its drag the Smooth tool smooths, in screen pixels. Alt smoothing with the /// Pencil, Paintbrush or Blob Brush uses the same radius. @@ -80,6 +84,9 @@ const BAND_WORK_PER_CALL: usize = 20_000; const PREVIEW_FIDELITY_PX: f64 = 0.5; /// The Smooth tool's Fidelity (screen pixels) until Smooth Tool Options sets another. const SMOOTH_FIDELITY: f64 = 2.5; +/// How far the pointer goes from the press point, in screen pixels, before a Shift-drag of the +/// Eraser takes the 45° step it lies nearest to. +const ERASER_SHIFT_PX: f64 = 3.0; /// The `fidelity` (points) the Pencil and the Paintbrush send `path.freehand` for `px` screen pixels /// at the current zoom, within the range the command takes @@ -176,7 +183,8 @@ pub struct GestureTool { /// The straight line is not constrained to 45° steps: the Pencil's Alt line, whose end snaps to /// Smart Guides as a stroke's end does, or the Knife's line while Shift is up. unconstrained: bool, - /// Axis selected during the current uninterrupted Shift interval, in degrees. + /// Axis selected during the current uninterrupted Shift interval, in degrees: the Blob Brush's + /// horizontal or vertical, or the Eraser's 45° step. shift_line: Option, /// "Merge only with selection": a Blob Brush stroke merges only with selected paths. pub merge_only_selection: bool, @@ -212,6 +220,8 @@ pub struct GestureTool { band: Cell>, /// The band last shown does not cover the whole drag yet; the next call adds to it. band_pending: Cell, + /// The pieces of a long drag's line shown so far ([`LinePreview`]). + line: Cell>, } /// The band a smoothing drag smooths, for the drag's first `used` points at `radius`, kept as its @@ -234,8 +244,8 @@ struct SmoothBand { dirty_long: BTreeSet, /// The band changed since `shown` was made. changed: bool, - /// The outline last finished. - shown: Option, + /// The outline last finished, shared with the overlays that show it until it is made again. + shown: Option>, /// The work done on long segments in the current call ([`BAND_WORK_PER_CALL`]). work: usize, } @@ -491,7 +501,7 @@ impl SmoothBand { /// The band's outline: the last one finished. While the band has changed since, the parts it /// changed are made again, until [`BAND_WORK_PER_CALL`] is spent in the call; when all are /// made, the outline is joined from them ([`SmoothBand::make_outline`]). - fn outline(&mut self) -> Option { + fn outline(&mut self) -> Option> { while self.changed { if !self.dirty_tiles.is_empty() || !self.dirty_long.is_empty() { if self.work >= BAND_WORK_PER_CALL { @@ -511,7 +521,7 @@ impl SmoothBand { } } } else { - self.shown = Some(self.make_outline()); + self.shown = Some(Arc::new(self.make_outline())); self.changed = false; } } @@ -898,6 +908,7 @@ impl GestureTool { area_pending: Cell::new(false), band: Cell::new(None), band_pending: Cell::new(false), + line: Cell::new(None), } } @@ -1019,9 +1030,10 @@ impl GestureTool { } /// Constrain a straight Pencil line from the Constrain Angle, a straight Knife cut from the - /// canvas axes, or the current Blob Brush sample. Blob Brush chooses an - /// axis once per uninterrupted Shift interval; samples already drawn never move. - /// A smoothing drag follows the pointer without a Shift constraint. + /// canvas axes, or the current Blob Brush or Eraser sample. The Blob Brush chooses an axis, + /// and the Eraser a 45° step from the Constrain Angle, once per uninterrupted Shift interval; + /// samples already drawn never move. A smoothing drag follows the pointer without a Shift + /// constraint. fn constrained(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Point { if self.straight && self.unconstrained { return p; @@ -1032,10 +1044,21 @@ impl GestureTool { let origin = if self.id == "knife" { 0.0 } else { cx.constrain_angle }; return start + vectorcraft_geom::constrain_angle_from(p - start, 45.0, origin); } - let Some(&start) = self.points.first().filter(|_| self.id == "blobBrush" && m.shift && !self.smoothing) else { + let shifts = (self.id == "blobBrush" && !self.smoothing) || self.id == "eraser"; + let Some(&start) = self.points.first().filter(|_| shifts && m.shift) else { self.shift_line = None; return p; }; + if self.id == "eraser" && self.shift_line.is_none() { + // The step is taken once the pointer is clear of the press point, in screen pixels at + // any zoom; until then the stroke waits at its last sample. + let v = p - start; + if v.hypot() * cx.zoom < ERASER_SHIFT_PX { + return self.points.last().copied().unwrap_or(start); + } + let c = vectorcraft_geom::constrain_angle_from(v, 45.0, cx.constrain_angle); + self.shift_line = Some(-c.y.atan2(c.x).to_degrees()); + } if self.shift_line.is_none() { // Raw press-to-pointer displacement in logical screen pixels along the constraint // axes. Zoom changes the document distance, not the activation tolerance. @@ -1055,6 +1078,16 @@ impl GestureTool { start + vectorcraft_geom::constrain_angle_from(p - start, 180.0, self.shift_line.unwrap_or(cx.constrain_angle)) } + /// [`Self::constrained`] for a drag to `p`: the Eraser's tip outline shows where its stroke + /// is, on the line of a Shift-drag. + fn constrained_drag(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Point { + let p = self.constrained(cx, p, m); + if self.id == "eraser" && self.tip_at.is_some() { + self.tip_at = Some(p); + } + p + } + /// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline /// `size` across at its angle and roundness (the Eraser's as the pen varies them while it /// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on @@ -1127,6 +1160,7 @@ impl GestureTool { self.area_pending.set(false); self.band.set(None); self.band_pending.set(false); + self.line.set(None); } /// The outline of the band a smoothing drag smooths: every point within `radius` of the drag, @@ -1139,8 +1173,9 @@ impl GestureTool { /// outside the squares, and one whose outlines cannot be combined adds nothing. Either way the /// band goes on past it. The work on such long segments stops for the call once /// [`BAND_WORK_PER_CALL`] is spent, and the drag is added to the band only once the outline of - /// what it holds is finished. - fn smooth_band(&self, radius: f64) -> Option { + /// what it holds is finished. The outline is the same shared path from one call to the next + /// until the band changes. + fn smooth_band(&self, radius: f64) -> Option> { let pts = &self.points; let &first = pts.first()?; let mut b = self @@ -1612,7 +1647,7 @@ impl Tool for GestureTool { } self.knife_shift(ev.mods); self.moved |= self.points.first().is_some_and(|start| p.distance(*start) > vectorcraft_geom::EPS); - let p = self.constrained(cx, p, ev.mods); + let p = self.constrained_drag(cx, p, ev.mods); let mut end = p; if self.grid_snaps(cx) && !self.smoothing && !self.straight { // Where the stroke would end on the grid or a pixel: taken on release. @@ -1818,7 +1853,7 @@ impl Tool for GestureTool { && has_selected_smooth_path(cx) && let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS)) { - o.push(Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: true }); + o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) }); } // A Blob Brush drag that smooths shows the Smooth tool's thin line. let width = match self.id { @@ -1851,17 +1886,34 @@ impl Tool for GestureTool { let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }]; area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j))); let paths = area.paths(&self.points); - o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 })); + o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None })); o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); self.area_pending.set(area.pending(&self.points)); self.area.set(Some(area)); } else if size_varies { // With Size on a mode that follows the pen, each step of the drag shows as wide as the - // tip the pen gives at its ends. - for (j, seg) in self.points.windows(2).enumerate() { - let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom; - o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false }); + // tip the pen gives at its ends. A long drag's steps are kept from call to call + // ([`LinePreview::segments`]). + let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32; + if self.points.len() > line::PIECE_SEGMENTS + 1 { + let mut kept = self.line.take().unwrap_or_default(); + for (j, path) in kept.segments(&self.points).into_iter().enumerate() { + o.push(Overlay::SharedPath { path, color, width: width_of(j), dash: None }); + } + self.line.set(Some(kept)); + } else { + for (j, seg) in self.points.windows(2).enumerate() { + o.push(Overlay::Path { path: polyline(seg), color, width: width_of(j), dashed: false }); + } } + } else if self.points.len() > line::PIECE_SEGMENTS + 1 { + // A long drag's line shows in pieces kept from call to call ([`LinePreview::pieces`]). + let mut kept = self.line.take().unwrap_or_default(); + let dashed = self.id == "knife"; + for piece in kept.pieces(&self.points) { + o.push(Overlay::SharedPath { path: piece.path, color, width, dash: dashed.then_some(piece.along) }); + } + self.line.set(Some(kept)); } else { o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" }); } diff --git a/crates/tools/src/draw2/gesture/line.rs b/crates/tools/src/draw2/gesture/line.rs new file mode 100644 index 0000000000..a2ed4beb4b --- /dev/null +++ b/crates/tools/src/draw2/gesture/line.rs @@ -0,0 +1,164 @@ +//! The line a drag shows while it is dragged where it does not show the area its tip covers (a +//! round Eraser tip, the Knife, the Pencil with Live preview off, a smoothing drag), kept in +//! pieces that later calls return again unchanged. +//! +//! A drag of more than [`PIECE_SEGMENTS`] segments is cut into pieces of that many segments. A +//! piece ends halfway along the segment after its last point, where the next piece starts, so that +//! a wide line turns at a piece's last point as one line does and no part of the line is drawn +//! twice. A piece the drag has gone past is built once and returned again as the +//! same shared path; only the last piece is built again, and only when the drag changed it. With +//! Size on a mode that follows the pen each segment shows at its own width, so each segment is +//! kept as its own path, and only a segment whose ends moved is built again. + +use std::sync::Arc; + +use vectorcraft_geom::{BezPath, Point}; + +use super::super::polyline; + +/// The segments of a drag from the first point of one piece of its line to the first point of the +/// next. +pub(super) const PIECE_SEGMENTS: usize = 64; + +/// A piece of the line along the drag's points `from` to `to`: from point `from`, or halfway to the +/// point after it in a piece other than the first, and up to point `to`, or halfway to it in a +/// piece the drag has gone past. +struct Piece { + path: Arc, + from: usize, + to: usize, + /// The drag's point `to` when the piece was built. + end: Point, + /// The length of the line before the piece's first point. + along: f64, + /// The length of the piece. + length: f64, +} + +/// A piece of the line to show ([`LinePreview::pieces`]). +pub(super) struct LinePiece { + /// The same shared path as in the call before while the piece did not change. + pub path: Arc, + /// The length of the line before the piece, where a dashed line's pattern goes on. + pub along: f64, +} + +/// The pieces of a long drag's line, as far as they are built. +#[derive(Default)] +pub(super) struct LinePreview { + /// The pieces the drag has gone past, in order. + settled: Vec, + /// The last piece, up to the drag's last point. + last: Option, + /// Each segment of the drag as its own path, with the points it runs between. + segments: Vec<(Point, Point, Arc)>, + /// The points copied into new paths by the last call. + built: usize, +} + +impl LinePreview { + /// The points copied into new paths by the last call. + #[cfg(test)] + pub(super) fn built(&self) -> usize { + self.built + } + + /// The pieces of the line through `pts`: the pieces kept from the call before while the drag + /// still runs through their points, and new ones for the rest. + pub(super) fn pieces(&mut self, pts: &[Point]) -> Vec { + self.built = 0; + // The drag no longer runs through the points of a kept piece (another drag, or a drag + // made again from its press). + let runs_through = |p: &Piece| pts.get(p.to) == Some(&p.end) && p.path.elements().first().and_then(|e| e.end_point()) == start(pts, p.from); + if let Some(k) = self.settled.iter().position(|p| !runs_through(p)) { + self.settled.truncate(k); + self.last = None; + } + // A piece settles once the drag has gone past its last point, which can still move. It + // then ends halfway along the segment after that point, so it is built again. + loop { + let from = self.settled.len() * PIECE_SEGMENTS; + let to = from + PIECE_SEGMENTS + 1; + if to + 1 >= pts.len() { + break; + } + let along = self.along_next(); + let piece = self.build(pts, from, to, true, along); + self.settled.push(piece); + } + let from = self.settled.len() * PIECE_SEGMENTS; + let to = pts.len().saturating_sub(1); + if to > from { + let along = self.along_next(); + // The last piece's points other than its last can change only with its last one, or + // with the drag's length. + let kept = + self.last.take().filter(|p| p.from == from && p.to == to && run(pts, from, to, false).is_some_and(|run| same_points(&p.path, run))); + self.last = Some(match kept { + Some(p) => p, + None => self.build(pts, from, to, false, along), + }); + } else { + self.last = None; + } + self.settled.iter().chain(&self.last).map(|p| LinePiece { path: Arc::clone(&p.path), along: p.along }).collect() + } + + /// Each segment of the line through `pts` as its own path: the same shared path as in the + /// call before while the segment's ends did not move. + pub(super) fn segments(&mut self, pts: &[Point]) -> Vec> { + self.built = 0; + let n = pts.len().saturating_sub(1); + self.segments.truncate(n); + let mut out = Vec::with_capacity(n); + for (j, w) in pts.windows(2).enumerate() { + match self.segments.get(j) { + Some((a, b, path)) if *a == w[0] && *b == w[1] => out.push(Arc::clone(path)), + _ => { + let path = Arc::new(polyline(w)); + self.built += 2; + match self.segments.get_mut(j) { + Some(kept) => *kept = (w[0], w[1], Arc::clone(&path)), + None => self.segments.push((w[0], w[1], Arc::clone(&path))), + } + out.push(path); + } + } + } + out + } + + /// The length of the line before the piece after the settled ones. + fn along_next(&self) -> f64 { + self.settled.last().map_or(0.0, |p| p.along + p.length) + } + + /// The piece along the points `from` to `to` of `pts` ([`run`]), `along` the line. + fn build(&mut self, pts: &[Point], from: usize, to: usize, settled: bool, along: f64) -> Piece { + let points: Vec = run(pts, from, to, settled).map(Iterator::collect).unwrap_or_default(); + self.built += points.len(); + let length = points.windows(2).map(|w| w[0].distance(w[1])).sum(); + Piece { path: Arc::new(polyline(&points)), from, to, end: pts.get(to).copied().unwrap_or_default(), along, length } + } +} + +/// Where a piece from the point `from` of `pts` starts: at the point in the first piece, else +/// halfway to the point after it, where the piece before ends. +fn start(pts: &[Point], from: usize) -> Option { + if from == 0 { pts.first().copied() } else { Some(pts.get(from)?.midpoint(*pts.get(from + 1)?)) } +} + +/// The points of the piece along the points `from` to `to` of `pts`: from its [`start`], through +/// the points after `from`, to point `to`, or, in a piece the drag has gone past (`settled`), to +/// halfway between the point before `to` and point `to`. +fn run(pts: &[Point], from: usize, to: usize, settled: bool) -> Option + '_> { + let first = start(pts, from)?; + let inner = pts.get(from + 1..if settled { to } else { to + 1 })?; + let last = if settled { Some(pts.get(to.checked_sub(1)?)?.midpoint(*pts.get(to)?)) } else { None }; + Some(std::iter::once(first).chain(inner.iter().copied()).chain(last)) +} + +/// Does `path` run through exactly the points `pts`? +fn same_points(path: &BezPath, mut pts: impl Iterator) -> bool { + path.elements().iter().all(|e| e.end_point().is_some() && e.end_point() == pts.next()) && pts.next().is_none() +} diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 2e417b38b2..550e7f9d32 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1195,7 +1195,14 @@ fn pencil_alt_smooths_within_the_smooth_tools_radius() { /// The dashed paths among the overlays. fn bands(t: &GestureTool, cx: &ToolContext) -> Vec { - t.overlays(cx).into_iter().filter_map(|o| if let Overlay::Path { path, dashed: true, .. } = o { Some(path) } else { None }).collect() + t.overlays(cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(path), + Overlay::SharedPath { path, dash: Some(_), .. } => Some((*path).clone()), + _ => None, + }) + .collect() } /// How far `q` is from the polyline through `pts`. @@ -1344,6 +1351,12 @@ fn smoothing_band_follows_a_long_drag() { assert_eq!(frames, (n - 1).div_ceil(BAND_STEP * BAND_STEPS_PER_CALL), "frames for {n} points"); check_band(&t, &cx, cx.tol(12.0)); assert!(!t.overlays_pending()); + // Once finished, the band shows as the same shared path each frame. + let band_of = |t: &GestureTool| { + t.overlays(&cx).into_iter().find_map(|o| if let Overlay::SharedPath { path, dash: Some(_), .. } = o { Some(path) } else { None }) + }; + let (a, b) = (band_of(&t), band_of(&t)); + assert!(a.zip(b).is_some_and(|(a, b)| std::sync::Arc::ptr_eq(&a, &b)), "the band is not made again"); let last = pts[pts.len() - 1]; t.pointer(&cx, &PointerEvent::new(PointerKind::Up, last.x, last.y)); // The next drag shows only its own band. @@ -1623,7 +1636,7 @@ fn smoothing_drag_shows_no_band_without_a_path_it_smooths() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 300.0)); let o = t.overlays(&cx); - assert!(!o.iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. })), "{o:?}"); + assert!(bands(&t, &cx).is_empty(), "{o:?}"); } /// An Alt smoothing drag uses the Smooth tool's Fidelity for Pencil, Paintbrush and Blob Brush. @@ -2032,6 +2045,76 @@ fn eraser_and_knife_exec_on_release() { assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.knife" && v["points"].as_array().unwrap().len() == 3)); } +/// With Shift held the Eraser's stroke stays on the line from the press point at the 45° step, +/// from the Constrain Angle, that the pointer lies nearest to once it is 3 screen pixels away: +/// horizontal, vertical or diagonal. The step holds until Shift is released, the tip outline shows +/// on the line, and the drag goes on freehand from the last sample on the line without moving it. +#[test] +fn eraser_shift_keeps_the_stroke_on_a_45_degree_line() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = GestureTool::new("eraser"); + let ev = |k, x, y, m| PointerEvent::new(k, x, y).with_mods(m); + let on_line = |q: Point, deg: f64| (q.x * deg.to_radians().sin() + q.y * deg.to_radians().cos()).abs() < 1e-9; + for zoom in [0.5, 1.0, 4.0] { + cx.zoom = zoom; + t.pointer(&cx, &ev(PointerKind::Down, 0.0, 0.0, shift)); + // Within 3 screen pixels of the press the stroke waits there, and so does its tip. + t.pointer(&cx, &ev(PointerKind::Drag, 2.0 / zoom, 2.0 / zoom, shift)); + assert_eq!(t.points, vec![Point::ZERO]); + assert_eq!(t.tip_at, Some(Point::ZERO)); + // 22° below the horizontal: the horizontal step, at the pointer's distance. + t.pointer(&cx, &ev(PointerKind::Drag, 10.0 / zoom, 4.0 / zoom, shift)); + let first = t.points[1]; + assert!((first.x - 116f64.sqrt() / zoom).abs() < 1e-9 && first.y.abs() < 1e-9, "{first:?}"); + assert_eq!(t.tip_at, Some(first)); + // The step holds while Shift stays down. + t.pointer(&cx, &ev(PointerKind::Drag, 3.0 / zoom, 20.0 / zoom, shift)); + assert!(t.points.iter().all(|q| q.y.abs() < 1e-9), "{:?}", t.points); + // Released, the drag goes on freehand from there. + t.pointer(&cx, &ev(PointerKind::Drag, 30.0 / zoom, 25.0 / zoom, Mods::default())); + assert_eq!(t.points.last(), Some(&Point::new(30.0 / zoom, 25.0 / zoom))); + assert_eq!(t.tip_at, Some(Point::new(30.0 / zoom, 25.0 / zoom))); + assert_eq!(t.points[1], first); + // Shift again takes a new step from the press point: the diagonal down and to the right. + t.pointer(&cx, &ev(PointerKind::Drag, 40.0 / zoom, 36.0 / zoom, shift)); + let q = *t.points.last().unwrap(); + assert!((q.x - q.y).abs() < 1e-9 && q.x > 0.0, "{q:?}"); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 50.0 / zoom, 44.0 / zoom, shift)); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(c, "path.eraseRegion"); + let last = v["points"].as_array().unwrap().last().unwrap().clone(); + let (x, y) = (last[0].as_f64().unwrap(), last[1].as_f64().unwrap()); + assert!((x - y).abs() < 1e-9 && x > 0.0, "{last}"); + } + // The steps go from the Constrain Angle, counter-clockwise on the page: at 30°, a drag at 70° + // takes the 75° step and one at 105° the 120° step, either way from the press. + cx.zoom = 1.0; + cx.constrain_angle = 30.0; + for (drag, step) in [(70.0_f64, 75.0), (105.0, 120.0), (-150.0, -150.0), (40.0, 30.0)] { + t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0, shift)); + let r = drag.to_radians(); + t.pointer(&cx, &ev(PointerKind::Drag, 100.0 + 20.0 * r.cos(), 100.0 - 20.0 * r.sin(), shift)); + let q = t.points[1] - Point::new(100.0, 100.0); + assert!(on_line(Point::new(q.x, q.y), step), "drag {drag}: {q:?}"); + assert!((q.hypot() - 20.0).abs() < 1e-9); + // Along the step's line both ways: back past the press stays on it. + let r = (step + 180.0).to_radians(); + t.pointer(&cx, &ev(PointerKind::Drag, 100.0 + 5.0 * r.cos() + 3.0, 100.0 - 5.0 * r.sin(), shift)); + let q = *t.points.last().unwrap() - Point::new(100.0, 100.0); + assert!(on_line(Point::new(q.x, q.y), step), "drag {drag} back: {q:?}"); + t.pointer(&cx, &ev(PointerKind::Up, 100.0, 100.0, Mods::default())); + } + // A Shift-drag released within 3 pixels of the press erases at the press. + cx.constrain_angle = 0.0; + t.pointer(&cx, &ev(PointerKind::Down, 20.0, 20.0, shift)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 22.0, 21.0, shift)); + assert!(matches!(&acts[0], Action::Exec(c, v) if c == "path.eraseRegion" && v["points"] == json!([[20.0, 20.0]])), "{acts:?}"); +} + /// An Alt-drag with the Eraser shows a marquee from the press point to the pointer, without the /// tip outline, and the release erases that rectangle; a drag back up and left gives the same /// kind of rectangle, measured from its top-left corner. @@ -2430,7 +2513,7 @@ fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt)); let o = t.overlays(&cx); - let [Overlay::Path { dashed: true, .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") }; + let [Overlay::SharedPath { dash: Some(_), .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") }; assert_eq!(*width, 1.0); assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}"); } @@ -2590,6 +2673,112 @@ fn the_settled_outline_of_a_long_drag_is_the_same_shared_path_each_frame() { } } +/// The points the last `overlays` call copied into new paths for a drag's line. +fn line_built(t: &GestureTool) -> usize { + let line = t.line.take(); + let built = line.as_ref().map_or(0, |l| l.built()); + t.line.set(line); + built +} + +/// The points of piece `k` of the line of a drag through `pts`. A piece other than the first starts +/// halfway along the segment after its first point, and a piece other than the last (`settled`) +/// ends halfway along the segment after its last point, where the next piece starts. +fn piece_points(pts: &[Point], k: usize, settled: bool) -> Vec { + let from = k * line::PIECE_SEGMENTS; + let to = if settled { from + line::PIECE_SEGMENTS } else { pts.len() - 1 }; + let mut want = vec![if k == 0 { pts[0] } else { pts[from].midpoint(pts[from + 1]) }]; + want.extend_from_slice(&pts[from + 1..=to]); + if settled { + want.push(pts[to].midpoint(pts[to + 1])); + } + want +} + +/// The line of a long round Eraser, Knife, Path Eraser or Pencil (Live preview off) drag shows in +/// pieces, and the steps of a round Eraser drag whose Size follows the pen each as its own path. +/// They come back from one call to the next, at any zoom, as the same shared paths, which the host +/// draws again without building them again; the call copies no point into a new path. A step of +/// the drag builds again only the last piece, or adds one step. The pieces run through every point +/// of the drag, each from where the one before ends, halfway along a segment, so no part of the +/// line is drawn twice, and the Knife's dashes go on from one piece to the next. +#[test] +fn the_line_of_a_long_drag_is_the_same_shared_pieces_each_frame() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let shared = |o: &[Overlay]| -> Vec<(std::sync::Arc, f32, Option)> { + o.iter() + .filter_map( + |o| if let Overlay::SharedPath { path, width, dash, .. } = o { Some((std::sync::Arc::clone(path), *width, *dash)) } else { None }, + ) + .collect() + }; + let points_of = |p: &BezPath| -> Vec { p.elements().iter().filter_map(|e| e.end_point()).collect() }; + let n = 3000; + for (id, pressure) in [("eraser", false), ("knife", false), ("pathEraser", false), ("pencil", false), ("eraser", true)] { + let mut t = GestureTool::new(id); + t.set_option("size", &json!(10)); + t.set_option("livePreview", &json!(false)); + if pressure { + t.set_option("sizeMode", &json!("pressure")); + t.set_option("sizeVariation", &json!(4)); + } + long_area_drag(&mut t, &cx, n, |i| if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 }); + let first = shared(&t.overlays(&cx)); + assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Path { .. })), "{id}: no path of the drag is built for the call alone"); + if pressure { + assert_eq!(first.len(), n - 1, "{id}: a path for each step"); + for (j, (path, _, dash)) in first.iter().enumerate() { + assert_eq!(points_of(path), t.points[j..=j + 1], "{id}: step {j}"); + assert_eq!(*dash, None); + } + } else { + assert!(first.len() > 1, "{id}: {} pieces", first.len()); + let mut along = 0.0; + for (k, (path, width, dash)) in first.iter().enumerate() { + let got = points_of(path); + assert_eq!(got, piece_points(&t.points, k, k + 1 < first.len()), "{id}: piece {k}"); + assert_eq!(*width, if id == "eraser" { 10.0 } else { 1.0 }, "{id}"); + match dash { + Some(at) => assert!(id == "knife" && (at - along).abs() < 1e-6, "{id}: piece {k} dashes from {at}, not {along}"), + None => assert_ne!(id, "knife"), + } + along += got.windows(2).map(|w| w[0].distance(w[1])).sum::(); + } + assert_eq!(first.len() - 1, (n - 3) / line::PIECE_SEGMENTS, "{id}: the last piece holds the points no settled piece holds"); + } + for zoom in [1.0, 4.0, 1.0] { + let again = shared(&t.overlays(&ToolContext { zoom, ..cx })); + assert_eq!(line_built(&t), 0, "{id}: at zoom {zoom}, no point is copied into a new path"); + assert_eq!(again.len(), first.len(), "{id}"); + assert!( + again.iter().zip(&first).all(|(a, b)| std::sync::Arc::ptr_eq(&a.0, &b.0)), + "{id}: at zoom {zoom}, every path is the one shown before" + ); + } + // One step more along the drag. + let s = n as f64; + let r = 150.0 + 100.0 * (s * 0.0071).sin(); + let (x, y) = (300.0 + r * (s * 0.04).cos(), 300.0 + r * (s * 0.04).sin()); + t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, x, y) }); + let after = shared(&t.overlays(&cx)); + let built = line_built(&t); + let kept = after.iter().filter(|a| first.iter().any(|f| std::sync::Arc::ptr_eq(&a.0, &f.0))).count(); + if pressure { + assert_eq!((built, after.len(), kept), (2, n, n - 1), "{id}: one step added"); + } else { + assert!(built <= line::PIECE_SEGMENTS + 2, "{id}: {built} points copied"); + assert_eq!(kept, first.len() - 1, "{id}: only the last piece is built again"); + } + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y)); + assert!(!acts.is_empty(), "{id}: the release still acts"); + assert!(t.line.take().is_none(), "{id}: the release drops the pieces"); + } +} + /// The outline a Blob Brush or Eraser drag shows does not change what its release sends: the same /// drag sends the same command whether or not its outline was drawn along the way. #[test] diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index d7ee8ecdd8..36bea9b231 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -421,6 +421,23 @@ impl DrawSnap { self.guides.clear(); } + /// Snap to Tangent for a circle drawn around `center`, its radius `r` set by the pointer at `p` + /// through the dragged `corner` (where [`Self::drag`] put it): the radius, within the Smart + /// Guides snapping tolerance of `r`, at which the circle touches nearby art + /// ([`Targets::tangent_radius`]), its guides replacing the last snap's. None, the guides kept, + /// with Smart Guides or Snap to Tangent off, pixels or the grid snapping instead (each read + /// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in + /// reach, or an anchor, center or crossing in reach of `p` or at `corner`. + pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option { + let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None }; + if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid { + return None; + } + let (radius, guides) = t.tangent_radius(center, p, corner, r, cx.tol(*tol))?; + self.guides = guides; + Some(radius) + } + /// Snap `p`, dragged since the press, with the targets the press gathered. pub fn drag(&mut self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> Point { if self.targets.is_none() { diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index e3e6abeef6..7341cf2713 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -107,6 +107,89 @@ pub(super) fn span(r: &Rect, x: bool) -> (f64, f64) { if x { (r.x0, r.x1) } else { (r.y0, r.y1) } } +/// Is `v` square to the direction `d` (both nonzero)? +fn square_to(v: Vec2, d: Vec2) -> bool { + let scale = v.hypot() * d.hypot(); + scale > 1e-18 && v.dot(d).abs() <= 1e-9 * scale +} + +/// Do the directions `a` and `b` (both nonzero) run the same way? +fn parallel(a: Vec2, b: Vec2) -> bool { + let scale = a.hypot() * b.hypot(); + scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale +} + +/// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn +/// with curves does: nearly square to the center all along, and its distance from the center +/// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`]) +/// strays outward from its radius by up to 0.0273%, so an ellipse whose axes differ by less than +/// that cannot be told from one. A circle around the center then lies along the curve. +fn runs_round(seg: &PathSeg, center: Point) -> bool { + const SAMPLES: [f64; 9] = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]; + if matches!(seg, PathSeg::Line(_)) { + return false; + } + let (mut lo, mut hi) = (f64::INFINITY, 0.0_f64); + for t in SAMPLES { + let (v, d) = (seg.eval(t) - center, seg_direction(seg, t)); + if v.dot(d).abs() > 2e-3 * v.hypot() * d.hypot() { + return false; + } + (lo, hi) = (lo.min(v.hypot()), hi.max(v.hypot())); + } + hi - lo <= 3e-4 * hi +} + +/// Whether a segment of `segs` other than the `i`th carries on past the end `at` of the `i`th +/// (its start when `at_start`) in the same direction: it has an end at `at` and runs away from +/// it the way the `i`th runs out through it, so the two join smoothly there rather than overlap. +fn continues_smoothly(segs: &[&PathSeg], i: usize, at: Point, at_start: bool) -> bool { + let Some(seg) = segs.get(i) else { return false }; + let d = end_direction(seg, at_start); + let out = if at_start { -d } else { d }; + let close = 1e-9 * (1.0 + at.x.abs().max(at.y.abs())); + segs.iter().enumerate().filter(|(j, _)| *j != i).any(|(_, s)| { + [(true, s.start()), (false, s.end())].into_iter().any(|(start, end)| { + let d = end_direction(s, start); + end.distance(at) <= close && parallel(if start { d } else { -d }, out) + }) + }) +} + +/// The direction `seg` runs at its start (`at_start`) or its end. Where a curve's handle lies on +/// its anchor the derivative there is zero, so the direction is taken toward the next control +/// point that differs from the anchor, the direction the curve leaves the anchor in. +fn end_direction(seg: &PathSeg, at_start: bool) -> Vec2 { + let mut points: Vec = match seg { + PathSeg::Line(l) => vec![l.p0, l.p1], + PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2], + PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3], + }; + if !at_start { + points.reverse(); + } + let Some((&anchor, rest)) = points.split_first() else { return Vec2::ZERO }; + let away = rest.iter().map(|q| *q - anchor).find(|v| v.hypot2() > 0.0).unwrap_or(Vec2::ZERO); + if at_start { away } else { -away } +} + +/// The points inside `seg` where the line from `center` meets it square, where a circle round +/// `center` touches it, with the segment's direction there. A straight segment has at most one, its +/// foot of the perpendicular. On a curve, besides the sign changes [`touch_params`] finds, a sample +/// where the line is square exactly counts too: a center straight out from a symmetric curve's +/// middle meets it square at t = 0.5. +fn radial_touches(seg: &PathSeg, center: Point) -> Vec<(Point, Vec2)> { + /// The samples checked for an exact square meeting, as [`touch_params`] samples the curve. + const STEPS: u32 = 24; + if let PathSeg::Line(l) = seg { + let d = l.p1 - l.p0; + let t = (center - l.p0).dot(d) / d.hypot2(); + return if t.is_finite() && t > 0.0 && t < 1.0 { vec![(l.p0 + d * t, d)] } else { vec![] }; + } + let sampled = (1..STEPS).map(|i| f64::from(i) / f64::from(STEPS)).filter(|&t| square_to(seg.eval(t) - center, seg_direction(seg, t))); + sampled.chain(touch_params(seg, center, true)).map(|t| (seg.eval(t), seg_direction(seg, t))).collect() +} + /// Along axis `x`, does dragging `handle` move the box's minimum edge (true) or maximum (false)? fn resize_moves_min_edge(handle: Handle, x: bool) -> Option { let (ax, ay) = handle.axes(); @@ -778,6 +861,74 @@ impl Targets { out } + /// Snap to Tangent for a circle drawn around `center` with radius `r`: the radius nearest `r`, + /// within `tol` of it, at which the circle touches a target segment (where the line from + /// `center` meets the path square, at a point the path runs smoothly through), and the guides + /// showing it. None with an anchor, a center or a crossing within `tol` of the pointer `p`, or + /// at `corner`, where the drawn point snapped to: those win as they do for a drawn point. At + /// most 256 segments are measured, the ones nearest `p` when more cross the ring round + /// `center` at radius `r`. + pub(super) fn tangent_radius(&self, center: Point, p: Point, corner: Point, r: f64, tol: f64) -> Option<(f64, Vec)> { + /// How many segments one pointer move measures at most. + const MAX_SEGMENTS: usize = 256; + let finite = [center.x, center.y, p.x, p.y, corner.x, corner.y, r, tol].iter().all(|v| v.is_finite()); + if !self.tangent || !finite || r < 0.0 || tol <= 0.0 { + return None; + } + if self.nearest_point(p, tol).is_some() || self.crossing(p, tol).is_some() { + return None; + } + // The corner snapped onto a point or a crossing: it lies on one, not merely near. + let on = |q: Point| q.distance(corner) <= 1e-9 * (1.0 + corner.x.abs().max(corner.y.abs())); + if self.nearest_point(corner, tol).is_some_and(|(q, _)| on(q)) || self.crossing(corner, tol).is_some_and(on) { + return None; + } + let (lo, hi) = (r - tol, r + tol); + // A segment can touch the circle only if part of its control bounds lies within the ring + // between `lo` and `hi` around the center. + let in_ring = |b: &Rect| { + let near = Point::new(center.x.clamp(b.x0, b.x1), center.y.clamp(b.y0, b.y1)).distance(center); + let far = (center.x - b.x0).abs().max((center.x - b.x1).abs()).hypot((center.y - b.y0).abs().max((center.y - b.y1).abs())); + near <= hi && far >= lo + }; + let mut best: Option<(f64, Point, Vec2)> = None; + let mut offer = |q: Point, d: Vec2| { + let rho = q.distance(center); + if rho > tol && (rho - r).abs() <= tol && best.is_none_or(|(b, ..)| (rho - r).abs() < (b - r).abs()) { + best = Some((rho, q, d)); + } + }; + let mut ring: Vec<&(Rect, PathSeg)> = self.segments.iter().filter(|(b, _)| in_ring(b)).collect(); + if ring.len() > MAX_SEGMENTS { + let from_p = |b: &Rect| Point::new(p.x.clamp(b.x0, b.x1), p.y.clamp(b.y0, b.y1)).distance(p); + ring.select_nth_unstable_by(MAX_SEGMENTS, |a, b| from_p(&a.0).total_cmp(&from_p(&b.0))); + ring.truncate(MAX_SEGMENTS); + } + let near: Vec<&PathSeg> = ring.into_iter().map(|(_, s)| s).collect(); + for (i, seg) in near.iter().enumerate() { + // A circle around the same center lies along such a curve rather than touching it. + if runs_round(seg, center) { + continue; + } + for (q, d) in radial_touches(seg, center) { + offer(q, d); + } + // At an end square to the center the circle touches the path only where the next + // segment carries on in the same direction: at a corner or an open end it meets it. + // That segment ends on the circle too, so it is in the ring; when more than + // MAX_SEGMENTS segments are in the ring and it is not among those kept, the end is not + // offered. + for (at_start, end) in [(true, seg.start()), (false, seg.end())] { + let d = end_direction(seg, at_start); + if square_to(end - center, d) && continues_smoothly(&near, i, end, at_start) { + offer(end, d); + } + } + } + let (rho, q, d) = best?; + Some((rho, self.touch_guides(center, q, false, d, tol))) + } + /// The segment extension nearest `p`, within `tol` of it (and `p` farther than that from the /// end it starts at): that end, its direction and where `p` lands on it. Where `p` is nearer /// the horizontal or the vertical through that end there is none: lining up with it ("align") diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 70f6422055..a9de5b1e0c 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -59,7 +59,7 @@ mod cursor; mod input; mod readout; -pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext}; +pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext, ordinary_isolation}; pub use cursor::Cursor; pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey}; pub use readout::Readout; @@ -73,10 +73,13 @@ pub enum Overlay { SelectionMarquee { rect: Rect, enclosed: bool, pointer: Point }, /// A path preview (e.g. pen rubber band) in a colour (RGB). Path { path: BezPath, color: [u8; 3], width: f32, dashed: bool }, - /// A solid path preview that later calls return again, as the same shared `path`, for as long - /// as it does not change (the settled outline of a long Blob Brush or Eraser drag). The host - /// can keep what it built to draw it while `path` is the same allocation. - SharedPath { path: std::sync::Arc, color: [u8; 3], width: f32 }, + /// A path preview that later calls return again, as the same shared `path`, for as long as it + /// does not change (the settled outline of a long Blob Brush or Eraser drag, the pieces of a long + /// drag's line). The host can keep what it built to draw it while `path` is the same allocation. + /// With `dash`, it is dashed as a dashed [`Overlay::Path`] is, from `dash` document units along + /// the dash pattern: the pieces of one line, each starting where the one before it ends, dash + /// as the whole line does. + SharedPath { path: std::sync::Arc, color: [u8; 3], width: f32, dash: Option }, /// A line segment (smart guide, handle line). Line { a: Point, b: Point, color: [u8; 3], dashed: bool }, /// An anchor square: filled = selected. diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 9eda809c03..0743036fb6 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -15,6 +15,10 @@ //! box's eight handles scales the selection, a press on the selection's centre point (Show Center) //! moves it, and one just outside a corner of its box turns it about that centre, as the Selection //! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477). +//! +//! With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) +//! takes the radius at which it touches a nearby path whenever its radius comes within the +//! snapping tolerance of it ([`DrawSnap::circle_radius`]). use serde_json::{Value, json}; use vectorcraft_doc::OrientedBox; @@ -92,6 +96,10 @@ pub struct ShapeTool { pub star_ratio: f64, /// The star's inner radius held while Ctrl/Cmd is down in a drag. inner: Option, + /// Where the last drag put the dragged corner of a circle drawn from its center, from the + /// center, when Snap to Tangent sized it ([`Self::tangent_circle`]); none when the pointer + /// sized it. Space moving the circle moves the corner it was drawn with there and clears it. + tangent_corner: Option, /// Line Segment Tool Options: the length and angle (degrees) a click's dialog opens with, and /// Fill Line (new lines take the current fill). pub line_length: f64, @@ -153,6 +161,7 @@ impl ShapeTool { corner_radius: 12.0, star_ratio: 0.5, inner: None, + tangent_corner: None, snap: DrawSnap::default(), line_length: 100.0, line_angle: 0.0, @@ -418,6 +427,27 @@ impl ShapeTool { } } + /// Snap to Tangent for a circle drawn from its center `s` (the Ellipse tool with Alt and + /// Shift): the dragged corner `p` moved toward or away from `s` so that the circle touches a + /// nearby path, when its radius is within the snapping tolerance of a touching one + /// ([`DrawSnap::circle_radius`]); `raw` is the pointer before snapping. The radius is measured + /// along the Constrain Angle's axes, as the drawn box is ([`turned_box`]). None for any other + /// shape or modifiers, or with `p` on `s`. + fn tangent_circle(&mut self, cx: &ToolContext, s: Point, raw: Point, p: Point, m: Mods) -> Option { + if self.id != "ellipse" || !(m.alt && m.shift) || m.space { + return None; + } + let axes = vectorcraft_geom::constrain_axes(cx.constrain_angle).unwrap_or(Affine::IDENTITY); + let back = axes.inverse(); + let (c, d) = (back * s, back * p - back * s); + let r = d.x.abs().max(d.y.abs()); + if r.is_nan() || r <= 0.0 { + return None; + } + let radius = self.snap.circle_radius(cx, s, raw, p, r)?; + Some(axes * (c + d * (radius / r))) + } + /// The command for a drag from `start` to `p` (snapped: a line's end already keeps Shift's /// angle). pub fn command(&self, start: Point, p: Point, m: Mods) -> (String, Value) { @@ -560,6 +590,7 @@ impl Tool for ShapeTool { } PointerKind::Drag => { let Some(mut s) = self.start else { return vec![] }; + let raw = ev.pos; let pos = self.snap.drag(cx, ev.pos, self.leave(cx, s, ev.mods).as_ref()); let ev = &PointerEvent { pos, ..*ev }; // The inner radius of the star the last drag showed, with the ratio it drew with: @@ -567,15 +598,28 @@ impl Tool for ShapeTool { // first arrives with the next position. let ratio = if self.mods.alt { straight_ratio(self.points).unwrap_or(self.star_ratio) } else { self.star_ratio }; let shown = (self.last - s).hypot() * ratio; + // Space moves a circle Snap to Tangent sized from the corner it was drawn with, so + // it keeps that size while it moves and after Space is let go. + if ev.mods.space + && self.began + && let Some(d) = self.tangent_corner.take() + { + self.last = s + d; + } space_moves(&mut s, &mut self.last, ev, self.began); self.start = Some(s); self.mods = ev.mods; if self.id == "star" { self.hold_inner(shown, s, ev.pos, ev.mods); } + // A circle from its center takes a radius that touches a nearby path. Whether the + // drag has begun is judged before that snap. + let dragged = ev.pos; + self.tangent_corner = self.tangent_circle(cx, s, raw, ev.pos, ev.mods).map(|q| q - s); + let ev = &PointerEvent { pos: self.tangent_corner.map_or(ev.pos, |d| s + d), ..*ev }; let mut out = vec![]; if !self.began { - if ev.pos.distance(s) < cx.tol(2.0) { + if dragged.distance(s) < cx.tol(2.0) { return out; } self.began = true; @@ -733,7 +777,9 @@ impl Tool for ShapeTool { let (w, h) = match self.id { "polygon" => ((self.last - s).x.abs(), (self.last - s).y.abs()), _ => { - let (r, _) = turned_box(s, self.last, self.mods, cx.constrain_angle); + // The corner Snap to Tangent moved a circle's to, as the preview draws it. + let corner = self.tangent_corner.map_or(self.last, |d| s + d); + let (r, _) = turned_box(s, corner, self.mods, cx.constrain_angle); (r.width(), r.height()) } }; diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index c76eef404e..4e0ee1d1dc 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -196,6 +196,356 @@ fn shift_square_alt_center() { assert_eq!(v, json!({"x": -10.0, "y": -10.0, "width": 20.0, "height": 20.0})); } +/// A 500 × 500 document holding `paths`. +fn doc_holding_paths(paths: impl IntoIterator) -> vectorcraft_doc::Document { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + for (i, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), i, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + d +} + +/// The box of the last preview of a drag: x, y, width, height. +fn previewed_box(a: &[Action]) -> [f64; 4] { + let Some(Action::Preview(_, v)) = a.last() else { panic!("no preview: {a:?}") }; + ["x", "y", "width", "height"].map(|k| v[k].as_f64().unwrap_or(f64::NAN)) +} + +/// An Alt+Shift drag with the Ellipse tool from `center` to `to`: the circle's box as previewed, +/// and the overlays it shows. +fn circle_drag(c: &ToolContext, center: Point, to: Point) -> ([f64; 4], Vec) { + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(both)); + let a = t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both)); + (previewed_box(&a), t.overlays(c)) +} + +fn tangent_label_at(o: &[Overlay], at: Point, within: f64) -> bool { + o.iter().any(|o| matches!(o, Overlay::Label { text, p, .. } if text == "tangent" && p.distance(at) <= within)) +} + +/// Snap to Tangent: a circle drawn from its center takes the radius at which it touches a nearby +/// straight path, with the "tangent" label at the touch point, also when the touch point is the +/// middle of the segment; the size label gives the circle as drawn. +#[test] +fn a_circle_from_its_center_snaps_its_radius_to_touch_a_line() { + // The line's ends and middle line up with none of the corners below. + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) }; + // The pointer makes the radius 98; the line is 100 below the center. + let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(203.0, 102.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.size_label(200.0, 200.0))), "{o:?}"); + // From the other side of the touching radius too (102). + let (b, _) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(205.0, 98.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + // Space moves the snapped circle and keeps its size. + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(both)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 203.0, 102.0).with_mods(both)); + // Space pressed with the pointer still moves the circle by no more than the snap moved its + // corner. + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 203.0, 102.0).with_mods(Mods { space: true, ..both })); + let b = previewed_box(&a); + assert!(b[2] == 200.0 && b[3] == 200.0 && (b[0] - 100.0).abs() <= 4.0 && (b[1] - 100.0).abs() <= 4.0, "{b:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 253.0, 152.0).with_mods(Mods { space: true, ..both })); + let b = previewed_box(&a); + assert!(b[2] == 200.0 && b[3] == 200.0 && (b[0], b[1]) != (100.0, 100.0), "moved, same size: {b:?}"); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.size_label(200.0, 200.0)))); + // Letting go of Space where the moved circle no longer touches the line keeps its size, and + // moving on grows it from there. + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 253.0, 152.0).with_mods(both)); + assert_eq!(previewed_box(&a), b, "Space let go"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 243.0, 142.0).with_mods(both)); + let (grown, moved) = (previewed_box(&a), Point::new(b[0] + 100.0, b[1] + 100.0)); + let radius = (243.0 - moved.x).abs().max((142.0 - moved.y).abs()); + assert!(grown[2] == 2.0 * radius && grown[3] == 2.0 * radius && radius > 105.0, "{grown:?} from {moved:?}"); + // Out of reach (radius 90): the pointer sizes it. + let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(203.0, 110.0)); + assert_eq!(b, [110.0, 110.0, 180.0, 180.0]); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); +} + +/// A circle drawn around a center outside another circle touches it from outside at the nearer +/// side and takes it inside at the farther side, the radii those of the closed form (the distance +/// between the centers less or plus the other radius) within the error of the curves that draw a +/// circle. A center inside a circle gives the inscribed circle; its touch point is an anchor of +/// the circle, where two segments join smoothly. A center at the circle's own center gets no snap: +/// every point is square to it. +#[test] +fn a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside() { + use vectorcraft_geom::shapes::ellipse; + // A circle of radius 50 around (350, 300), its center 50√13 from (200, 200). + let d = doc_holding_paths([ellipse(Rect::new(300.0, 250.0, 400.0, 350.0))]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (center, between) = (Point::new(200.0, 200.0), 50.0 * 13f64.sqrt()); + let toward = Vec2::new(150.0, 100.0) / between; + for (radius, pointer) in [(between - 50.0, Vec2::new(20.0, -(between - 52.0))), (between + 50.0, Vec2::new(-20.0, between + 48.0))] { + let (b, o) = circle_drag(&c, center, center + pointer); + assert!((b[2] / 2.0 - radius).abs() < 0.02 && b[2] == b[3], "{b:?}, want radius {radius}"); + assert!(tangent_label_at(&o, center + toward * radius, 0.2), "{o:?}"); + } + // Concentric: no tangent snap. + let (_, o) = circle_drag(&c, Point::new(350.0, 300.0), Point::new(374.0, 252.0)); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); + // Ellipses with radii 10010 and 10000, or 1001 and 1000, around the center are nearly square + // to it all round, but they are not circles: a circle touches each at the ends of its axes. + for (rx, ry) in [(10_010.0, 10_000.0), (1001.0, 1000.0)] { + let d = doc_holding_paths([ellipse(Rect::new(250.0 - rx, 250.0 - ry, 250.0 + rx, 250.0 + ry))]); + let c = cx(&d, &s, &p); + let (_, o) = circle_drag(&c, Point::new(250.0, 250.0), Point::new(280.0, 252.0 - ry)); + assert!(tangent_label_at(&o, Point::new(250.0, 250.0 - ry), 1e-6), "{rx} × {ry}: {o:?}"); + } + let near = |b: [f64; 4], want: [f64; 4]| b.iter().zip(want).all(|(a, w)| (a - w).abs() < 1e-6); + // Inside a circle of radius 150 around (250, 250), 50 from its center: the inscribed circle has + // radius 100. + let d = doc_holding_paths([ellipse(Rect::new(100.0, 100.0, 400.0, 400.0))]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, Point::new(200.0, 250.0), Point::new(203.0, 152.0)); + assert!(near(b, [100.0, 150.0, 200.0, 200.0]), "{b:?}"); + assert!(tangent_label_at(&o, Point::new(100.0, 250.0), 1e-6), "{o:?}"); +} + +/// The touch point can fall inside a curved segment: the radius is the distance to the nearest +/// point of the curve, measured here by sampling the path's own segments densely. +#[test] +fn a_circle_from_its_center_snaps_to_touch_a_curve() { + use vectorcraft_geom::ParamCurve; + let path = vectorcraft_geom::shapes::ellipse(Rect::new(300.0, 100.0, 500.0, 200.0)); + let center = Point::new(250.0, 300.0); + let sp = &path.subpaths[0]; + let (want, at) = (0..sp.segment_count()) + .flat_map(|i| (0..=20_000).map(move |k| (i, f64::from(k) / 20_000.0))) + .map(|(i, t)| sp.segment(i).eval(t)) + .map(|q| (q.distance(center), q)) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .unwrap(); + let d = doc_holding_paths([path]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let r = want - 2.0; + let (b, o) = circle_drag(&c, center, center + Vec2::new(-r * 0.3, r)); + assert!((b[2] / 2.0 - want).abs() < 1e-4 && (b[3] / 2.0 - want).abs() < 1e-4, "radius {} want {want}", b[2] / 2.0); + assert!(tangent_label_at(&o, at, 1e-2), "{at:?} {o:?}"); + // Straight out from a symmetric curve's middle (t = 0.5, (200, 262.5)), 162.5 from (200, 100). + let mut bump = vectorcraft_geom::BezPath::new(); + bump.move_to((100.0, 300.0)); + bump.curve_to((150.0, 250.0), (250.0, 250.0), (300.0, 300.0)); + let d = doc_holding_paths([vectorcraft_geom::PathData::from_bezpath(&bump)]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, Point::new(200.0, 100.0), Point::new(40.0, 40.0)); + assert!((b[2] - 325.0).abs() < 1e-9 && (b[3] - 325.0).abs() < 1e-9, "{b:?}"); + assert!(tangent_label_at(&o, Point::new(200.0, 262.5), 1e-9), "{o:?}"); +} + +/// The snap is Snap to Tangent's, under Smart Guides: off, the pointer sizes the circle. An +/// ellipse (no Shift) and a box drawn from a corner (no Alt) do not snap. An open path's end and +/// a corner square to the center are where a circle meets the path rather than touches it, so +/// neither is offered. +#[test] +fn a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch() { + let line = vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0)); + let d = doc_holding_paths([line]); + let (s, p) = (Selection::default(), paint()); + // The pointer makes the radius 98, 2 short of touching the line. + let (center, to) = (Point::new(200.0, 200.0), Point::new(215.0, 102.0)); + for off in [ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }, ToolContext { smart_guides: false, ..cx(&d, &s, &p) }] { + assert_eq!(circle_drag(&off, center, to).0, [102.0, 102.0, 196.0, 196.0]); + } + let c = cx(&d, &s, &p); + assert_eq!(circle_drag(&c, center, to).0, [100.0, 100.0, 200.0, 200.0], "on, it snaps"); + for (mods, want) in + [(Mods { alt: true, ..Mods::default() }, [185.0, 102.0, 30.0, 196.0]), (Mods { shift: true, ..Mods::default() }, [200.0, 102.0, 98.0, 98.0])] + { + let mut t = ShapeTool::new("ellipse"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(mods)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods)); + assert_eq!(previewed_box(&a), want, "{mods:?}"); + } + // The line's left end is square below (60, 200), but it is an open end, also with a second + // line starting there the same way, which overlaps it rather than carrying it on. + assert_eq!(circle_drag(&c, Point::new(60.0, 200.0), Point::new(63.0, 102.0)).0, [-38.0, 102.0, 196.0, 196.0]); + let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1)); + let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((60.0, 300.0), (200.0, 300.0))]); + let c = cx(&d, &s, &p); + assert_eq!(circle_drag(&c, Point::new(60.0, 200.0), Point::new(63.0, 102.0)).0, [-38.0, 102.0, 196.0, 196.0]); + // Two lines end to end in one direction meet smoothly under (200, 200): the circle touches there. + let d = doc_holding_paths([line((60.0, 300.0), (200.0, 300.0)), line((200.0, 300.0), (380.0, 300.0))]); + let c = cx(&d, &s, &p); + assert_eq!(circle_drag(&c, center, to).0, [100.0, 100.0, 200.0, 200.0]); + // A rectangle's corner (200, 200) is 100√2 from (300, 300), diagonal to both its sides. + let (d, _) = doc_with_rect(); + let c = cx(&d, &s, &p); + let r = 100.0 * 2f64.sqrt() - 2.0; + let (b, _) = circle_drag(&c, Point::new(300.0, 300.0), Point::new(300.0 + r, 300.0 + r * 0.5)); + assert!((b[2] - 2.0 * r).abs() < 1e-9, "{b:?}"); +} + +/// An anchor the dragged corner snapped to wins over the tangent radius, as it does for a drawn +/// point. With more segments near the radius than one move measures, the ones nearest the pointer +/// are measured. +#[test] +fn a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer() { + let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1)); + let (s, p) = (Selection::default(), paint()); + let center = Point::new(200.0, 200.0); + // Shift keeps the corner on the diagonal, and it slides onto the anchor (297, 103): radius 97. + let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((297.0, 103.0), (297.0, 40.0))]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0)); + assert_eq!(b, [103.0, 103.0, 194.0, 194.0]); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); + // A corner that only lines up with an anchor near it, (300, 104), still takes the tangent. + let d = doc_holding_paths([line((60.0, 300.0), (380.0, 300.0)), line((300.0, 104.0), (300.0, 40.0))]); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}"); + // 300 short segments pointing at the center cross the ring above it, ahead of the line below. + let spokes = (0..300).map(|i| { + let a = (-55.0 + 110.0 * f64::from(i) / 299.0_f64).to_radians(); + let at = |r: f64| (200.0 + r * a.sin(), 200.0 - r * a.cos()); + line(at(95.0), at(105.0)) + }); + let d = doc_holding_paths(spokes.chain([line((60.0, 300.0), (380.0, 300.0))])); + let c = cx(&d, &s, &p); + // The press lines up with a spoke's anchor, so the center moves by less than a point. + let (b, o) = circle_drag(&c, center, Point::new(215.0, 298.0)); + assert!((b[2] - 200.0).abs() < 1e-9 && (b[3] - 200.0).abs() < 1e-9 && (b[1] - 100.0).abs() < 1e-9, "{b:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Label { text, p, .. } if text == "tangent" && (p.y - 300.0).abs() < 1e-9)), "{o:?}"); +} + +/// With a Constrain Angle the radius is measured, and the snapped box rebuilt, along the turned +/// axes: the circle still touches the line. +#[test] +fn a_circle_snapped_to_touch_keeps_to_the_constrain_angle() { + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(0.0, 300.0), Point::new(450.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { constrain_angle: 30.0, ..cx(&d, &s, &p) }; + let axes = vectorcraft_geom::constrain_axes(30.0).unwrap(); + let center = Point::new(200.0, 200.0); + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, center.x, center.y).with_mods(both)); + let to = center + (axes * Point::new(-40.0, -97.0)).to_vec2(); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + let (w, h) = (v["width"].as_f64().unwrap(), v["height"].as_f64().unwrap()); + assert!((w - 200.0).abs() < 1e-9 && (h - 200.0).abs() < 1e-9, "{v}"); + assert!((v["rotation"].as_f64().unwrap() + 30.0).abs() < 1e-9, "{v}"); + let mid = Point::new(v["x"].as_f64().unwrap() + w / 2.0, v["y"].as_f64().unwrap() + h / 2.0); + assert!(mid.distance(center) < 1e-9, "centered on the press: {mid:?}"); + // Space pressed with the pointer still keeps the size and moves the circle by no more than + // the snap moved its corner. + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(Mods { space: true, ..both })); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + let (w, h) = (v["width"].as_f64().unwrap(), v["height"].as_f64().unwrap()); + assert!((w - 200.0).abs() < 1e-9 && (h - 200.0).abs() < 1e-9, "{v}"); + let mid = Point::new(v["x"].as_f64().unwrap() + w / 2.0, v["y"].as_f64().unwrap() + h / 2.0); + assert!(mid.distance(center) <= 4.0, "{mid:?}"); +} + +/// Snap to Grid and pixel snapping place the drawn point instead of the tangent snap, also when +/// one is turned on while the circle is dragged out. Snap to Tangent turned off while dragging +/// stops the snap. +#[test] +fn a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels() { + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let on = cx(&d, &s, &p); + let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) }; + let pixels = ToolContext { snap_to_pixel: true, pixel_snap: crate::PixelSnap { drawing: true, ..on.pixel_snap }, ..cx(&d, &s, &p) }; + let no_tangent = ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }; + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let drag = |press: &ToolContext, moved: &ToolContext, to: Point| { + let mut t = ShapeTool::new("ellipse"); + t.pointer(press, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(both)); + let a = t.pointer(moved, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(both)); + (previewed_box(&a), t.overlays(moved)) + }; + let tangent = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")); + // The pointer makes the radius 98: the snap would make it 100. + let to = Point::new(203.0, 102.0); + assert_eq!(drag(&on, &on, to).0, [100.0, 100.0, 200.0, 200.0], "the snap applies"); + // Pixels round (203.2, 102.2) to (203, 102): radius 98. + let to = Point::new(203.2, 102.2); + for (press, moved) in [(&pixels, &pixels), (&on, &pixels)] { + let (b, o) = drag(press, moved, to); + assert_eq!(b, [102.0, 102.0, 196.0, 196.0]); + assert!(!tangent(&o), "{o:?}"); + } + // The grid (every 9 points) puts the corner on (207, 99): radius 101 from (200, 200), or 99 + // from (198, 198), where the grid puts a press made with it on. + for (press, moved, want) in [(&grid, &grid, [99.0, 99.0, 198.0, 198.0]), (&on, &grid, [99.0, 99.0, 202.0, 202.0])] { + let (b, o) = drag(press, moved, to); + assert_eq!(b, want); + assert!(!tangent(&o), "{o:?}"); + } + let (b, o) = drag(&on, &no_tangent, Point::new(203.0, 102.0)); + assert_eq!(b, [102.0, 102.0, 196.0, 196.0]); + assert!(!tangent(&o), "{o:?}"); +} + +/// A press and a small jitter is a click, not a drag, even when the tangent snap would size the +/// circle at the jittered pointer large enough to begin a drag. +#[test] +fn a_jittered_alt_shift_press_beside_a_path_is_a_click() { + // With a Constrain Angle, Shift does not hold the corner on the page's diagonal, which would + // take it onto the line. + let d = doc_holding_paths([vectorcraft_geom::shapes::line(Point::new(60.0, 300.0), Point::new(380.0, 300.0))]); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { constrain_angle: 30.0, ..cx(&d, &s, &p) }; + let both = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = ShapeTool::new("ellipse"); + // 5.5 above the line, beyond the snapping tolerance of 4. The jitter of 1.9 makes the radius + // 1.9 cos 30°, about 1.65, within 4 of the touching radius 5.5. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 294.5).with_mods(both)); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 201.9, 294.5).with_mods(both)), vec![]); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 201.9, 294.5).with_mods(both)); + assert!(!a.contains(&Action::Commit), "{a:?}"); +} + +/// An anchor or a crossing within the snapping tolerance of the pointer takes the point, and the +/// circle is not sized to touch the line. +#[test] +fn a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer() { + let line = |a: (f64, f64), b: (f64, f64)| vectorcraft_geom::shapes::line(Point::new(a.0, a.1), Point::new(b.0, b.1)); + let (s, p) = (Selection::default(), paint()); + let center = Point::new(200.0, 200.0); + let base = line((60.0, 300.0), (380.0, 300.0)); + // An anchor at (205, 104), and two lines crossing there. + for extra in [vec![line((205.0, 104.0), (260.0, 40.0))], vec![line((185.0, 84.0), (225.0, 124.0)), line((185.0, 124.0), (225.0, 84.0))]] { + let d = doc_holding_paths(std::iter::once(base.clone()).chain(extra)); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, center, Point::new(203.0, 102.0)); + assert!(b[2] != 200.0, "{b:?}"); + assert!(!o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "tangent")), "{o:?}"); + } +} + +/// A path whose anchor below the center joins two straight curves with their handles drawn back +/// onto that anchor runs smoothly through it: the circle touches it there. +#[test] +fn a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles() { + let mut run = vectorcraft_geom::BezPath::new(); + run.move_to((60.0, 300.0)); + run.curve_to((100.0, 300.0), (200.0, 300.0), (200.0, 300.0)); + run.curve_to((200.0, 300.0), (300.0, 300.0), (380.0, 300.0)); + let d = doc_holding_paths([vectorcraft_geom::PathData::from_bezpath(&run)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (b, o) = circle_drag(&c, Point::new(200.0, 200.0), Point::new(215.0, 102.0)); + assert_eq!(b, [100.0, 100.0, 200.0, 200.0]); + assert!(tangent_label_at(&o, Point::new(200.0, 300.0), 1e-9), "{o:?}"); +} + /// General › Constrain Angle: a Shift-drag squares along the turned axes, and the shape turns /// by the angle about its centre. #[test] diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index b489e4dd82..7bb59c79b1 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -72,7 +72,7 @@ pub use gradient::TracedGradient; pub use mosaic::mosaic; pub use opaque::{ALPHA_MAX_DECODE_BYTES, OUTLINE_MAX_ANCHORS, OUTLINE_MAX_PIXELS, decode_alpha, opaque_outline}; pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize}; -pub use seam::{SEAM_WIDTH, seam_fills}; +pub use seam::{SeamFills, seam_fills}; pub use shapes::TracedShape; use subpixel::Crack; diff --git a/crates/trace/src/seam.rs b/crates/trace/src/seam.rs index 726916e240..b0c6447d8a 100644 --- a/crates/trace/src/seam.rs +++ b/crates/trace/src/seam.rs @@ -6,19 +6,38 @@ //! under every path, fills those pixels with that color: drawing the two paths over it then gives //! each pixel the colors of the two paths in the shares each covers. The paths themselves are not //! changed, and an edge a path shares with no other path (the image's border, a transparent area, -//! a color left out) gets no stroke. +//! a color left out) gets no stroke. The strokes are clipped to the image's box. Where a shared +//! edge ends at, or runs within half the stroke's width of, a transparent area or a color left +//! out, its stroke can reach that far into that area. use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; -use super::params::{Method, Mode, TraceParams}; -use super::pipeline::TracedPath; +use crate::{Method, Mode, TraceParams, TracedPath}; /// How wide each seam fill's stroke is, in pixels: it covers every pixel the shared edge passes /// through, at any angle (a pixel's corner is up to 0.71 px from a line through it). -pub const SEAM_WIDTH: f64 = 1.5; +const SEAM_WIDTH: f64 = 1.5; + +/// The seam fills of an Abutting trace ([`seam_fills`]). +#[derive(Clone, Debug, PartialEq)] +pub struct SeamFills { + /// For each color, one path stroked 1.5 pixels wide along the edges where a filled path of + /// that color meets a filled path drawn after it, with `color` and `gradient` that path's; the + /// paths with a gradient get one each. Bottom-most first, as the paths they lie under. + pub strokes: Vec, + /// The area to clip `strokes` to, in the same pixel coordinates: the image's box. + pub clip: PathData, +} + +impl SeamFills { + /// The anchors of the strokes and the clip together. + pub fn anchor_count(&self) -> usize { + self.strokes.iter().map(|s| s.path.anchor_count()).sum::() + self.clip.anchor_count() + } +} /// A segment, the same for the segment and the segment run backwards: two 64-bit hashes of its /// points' bits, 16 bytes a segment instead of 64. Two different segments with the same key would @@ -36,18 +55,23 @@ fn key(a: &Anchor, b: &Anchor) -> Key { (u128::from(hash(0)) << 64) | u128::from(hash(1)) } -/// The seam fills of a trace made with `params`: for Abutting with Fills (not Flat Logo), thin -/// strokes to draw under every path of `paths` (bottom-most first). For each color, one path -/// stroked [`SEAM_WIDTH`] pixels wide along the edges where a filled path of that color meets a -/// filled path drawn after it, with `color` and `gradient` that path's; the paths with a gradient -/// get one each. Bottom-most first, as the paths they lie under. The stroke has at most as many -/// anchors as `paths` (each of its segments is a segment of a path), and finding them keeps about -/// 40 bytes for each segment of `paths` while it runs. Empty for any other trace. -pub fn seam_fills(paths: &[TracedPath], params: &TraceParams) -> Vec { +/// The seam fills of a trace of a `size` (width, height in pixels) image made with `params`, for +/// Abutting with Fills (not Flat Logo): strokes to draw under every path of `paths` (bottom-most +/// first), clipped to the image's box. Filled paths that became a live shape (Shapes) take no part: +/// their outline is not the traced one. The strokes have at most as many anchors as `paths` (each +/// of their segments is a segment of a path), and the clip has four; finding them keeps about 40 +/// bytes for each segment of `paths` while it runs. `None` for any other trace, or when no filled +/// paths share an edge. +pub fn seam_fills(paths: &[TracedPath], params: &TraceParams, size: (u32, u32)) -> Option { if params.method != Method::Abutting || !params.fills || params.mode == Mode::Logo { - return vec![]; + return None; } - fills(paths) + fills(paths, size) +} + +/// Whether `p` takes part in the seam fills: filled, and drawn with its traced outline. +fn filled(p: &TracedPath) -> bool { + p.stroke.is_none() && p.shape.is_none() } /// The segments of `sp`: each anchor and the one after it (back to the first, if closed). @@ -57,11 +81,11 @@ fn segments(sp: &SubPath) -> impl Iterator { (0..count).filter_map(move |k| Some((sp.anchors.get(k)?, sp.anchors.get((k + 1) % n)?))) } -/// [`seam_fills`] of Abutting `paths`, whatever the settings. -fn fills(paths: &[TracedPath]) -> Vec { +/// [`seam_fills`] of Abutting `paths` traced from a `size` image, whatever the settings. +fn fills(paths: &[TracedPath], size: (u32, u32)) -> Option { // For each segment, the first path it is in, and whether another path has it too. let mut owner: HashMap = HashMap::new(); - for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) { + for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) { for sp in &p.path.subpaths { for (a, b) in segments(sp).filter(|(a, b)| a.p != b.p) { let e = owner.entry(key(a, b)).or_insert((i, false)); @@ -74,11 +98,10 @@ fn fills(paths: &[TracedPath]) -> Vec { // One fill per color (per path, for a gradient), in the order of the first path it lies under. let mut out: Vec = vec![]; let mut by_color: HashMap<[u8; 3], usize> = HashMap::new(); - for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) { + for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) { let mut runs: Vec = vec![]; for sp in &p.path.subpaths { - let lower = |a: &Anchor, b: &Anchor| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true)); - let marks: Vec = segments(sp).map(|(a, b)| lower(a, b)).collect(); + let marks: Vec = segments(sp).map(|(a, b)| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true))).collect(); let n = sp.anchors.len(); if marks.is_empty() { continue; @@ -129,7 +152,12 @@ fn fills(paths: &[TracedPath]) -> Vec { } } } - out + if out.is_empty() { + return None; + } + let (w, h) = (f64::from(size.0), f64::from(size.1)); + let clip = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)], true)); + Some(SeamFills { strokes: out, clip }) } /// An open run of anchors: the last one has no handle out. @@ -143,13 +171,18 @@ fn open_run(mut run: Vec) -> SubPath { #[cfg(test)] mod tests { use super::*; - use crate::{Method, Mode, Raster, TraceParams, trace}; + use crate::{Method, Mode, Raster, TraceParams, TracedGradient, TracedShape, trace}; fn polygon(rings: &[&[(f64, f64)]], color: u8) -> TracedPath { let subpaths = rings.iter().map(|r| SubPath::polyline(&r.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), true)).collect(); TracedPath { path: PathData::new(subpaths), color: [color; 3], pixels: 1, stroke: None, shape: None, gradient: None, square_caps: false } } + /// The strokes of [`fills`] for `paths` in a box that no test path reaches the border of. + fn strokes(paths: &[TracedPath]) -> Vec { + fills(paths, (100, 100)).map(|f| f.strokes).unwrap_or_default() + } + fn points(sp: &SubPath) -> Vec<(f64, f64)> { sp.anchors.iter().map(|a| (a.p.x, a.p.y)).collect() } @@ -163,7 +196,7 @@ mod tests { fn a_shared_edge_gets_a_stroke_in_the_color_of_the_path_drawn_first() { let left = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); - let fills = fills(&[left.clone(), right.clone()]); + let fills = strokes(&[left.clone(), right.clone()]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!((fills[0].color, fills[0].stroke, fills[0].gradient.as_ref()), ([10; 3], Some(SEAM_WIDTH), None)); assert_eq!(fills[0].path.subpaths.len(), 1); @@ -171,7 +204,7 @@ mod tests { assert!(!sp.closed); assert_eq!(points(sp), [(2.0, 0.0), (2.0, 2.0)]); // Drawn the other way round, the stroke takes the other color. - let swapped = super::fills(&[right, left]); + let swapped = strokes(&[right, left]); assert_eq!(swapped.len(), 1); assert_eq!((swapped[0].color, points(&swapped[0].path.subpaths[0])), ([20; 3], vec![(2.0, 2.0), (2.0, 0.0)])); } @@ -181,7 +214,7 @@ mod tests { let hole: &[(f64, f64)] = &[(2.0, 2.0), (2.0, 4.0), (4.0, 4.0), (4.0, 2.0)]; let around = polygon(&[&[(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)], hole], 10); let island = polygon(&[&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]], 20); - let fills = fills(&[around, island]); + let fills = strokes(&[around, island]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].color, [10; 3]); assert_eq!(fills[0].path.subpaths.len(), 1); @@ -195,7 +228,7 @@ mod tests { // at the same point. let left = polygon(&[&[(2.0, 1.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0), (2.0, 0.0)]], 10); let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0), (2.0, 1.0)]], 20); - let fills = fills(&[left, right]); + let fills = strokes(&[left, right]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].path.subpaths.len(), 1); assert_eq!(points(&fills[0].path.subpaths[0]), [(2.0, 0.0), (2.0, 1.0), (2.0, 2.0)]); @@ -204,11 +237,15 @@ mod tests { #[test] fn edges_shared_with_no_other_filled_path_get_no_stroke() { let square = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); - assert_eq!(fills(std::slice::from_ref(&square)), []); - // A stroked line along the square's edge is not a filled neighbour. - let mut line = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); - line.stroke = Some(1.0); - assert_eq!(fills(&[square, line]), []); + assert_eq!(fills(std::slice::from_ref(&square), (100, 100)), None); + // A stroked path along the square's edge is not a filled neighbor. + let mut stroked = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); + stroked.stroke = Some(1.0); + assert_eq!(fills(&[square.clone(), stroked], (100, 100)), None); + // Nor is a path drawn as a live shape, whose outline is not the traced one. + let mut shape = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); + shape.shape = Some(TracedShape::Rectangle { center: Point::new(3.0, 1.0), width: 2.0, height: 2.0, radius: 0.0, rotation: 0.0 }); + assert_eq!(fills(&[square, shape], (100, 100)), None); } #[test] @@ -216,9 +253,34 @@ mod tests { let a = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); let b = polygon(&[&[(0.0, 4.0), (2.0, 4.0), (2.0, 6.0), (0.0, 6.0)]], 10); let c = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 6.0), (2.0, 6.0), (2.0, 4.0), (2.0, 2.0)]], 20); - let fills = fills(&[a, b, c]); + let fills = strokes(&[a.clone(), b.clone(), c.clone()]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].path.subpaths.iter().map(points).collect::>(), [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]]); + // With a gradient each, the two paths of one color get a stroke each, with their gradient. + let ramp = |to: u8| TracedGradient { start: Point::new(0.0, 0.0), end: Point::new(2.0, 0.0), stops: vec![(0.0, [10; 3]), (1.0, [to; 3])] }; + let (mut a, mut b) = (a, b); + (a.gradient, b.gradient) = (Some(ramp(30)), Some(ramp(40))); + let fills = strokes(&[a.clone(), b.clone(), c]); + assert_eq!(fills.len(), 2, "{fills:?}"); + assert_eq!(fills.iter().map(|f| f.gradient.clone()).collect::>(), [a.gradient, b.gradient]); + assert_eq!( + fills.iter().map(|f| points(&f.path.subpaths[0])).collect::>(), + [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]] + ); + } + + #[test] + fn the_strokes_are_clipped_to_the_images_box() { + // A diagonal edge meeting the border: a corner of the stroke's butt end reaches past the + // box, and the clip is the box. + let lower = polygon(&[&[(0.0, 0.0), (3.0, 0.0), (1.0, 2.0), (0.0, 2.0)]], 10); + let upper = polygon(&[&[(3.0, 0.0), (4.0, 0.0), (4.0, 2.0), (1.0, 2.0)]], 20); + let diagonal = fills(&[lower, upper], (4, 2)).unwrap(); + assert_eq!(points(&diagonal.strokes[0].path.subpaths[0]), [(3.0, 0.0), (1.0, 2.0)]); + assert_eq!(diagonal.clip.subpaths.len(), 1); + assert!(diagonal.clip.subpaths[0].closed); + assert_eq!(points(&diagonal.clip.subpaths[0]), [(0.0, 0.0), (4.0, 0.0), (4.0, 2.0), (0.0, 2.0)]); + assert_eq!(diagonal.anchor_count(), 2 + 4); } /// Two colors side by side, the edge between them anti-aliased at `x = 10.4`. @@ -239,9 +301,9 @@ mod tests { let params = color(Method::Abutting); let res = trace(&two_colors(), ¶ms); assert_eq!(res.paths.len(), 2, "{res:?}"); - let seams = seam_fills(&res.paths, ¶ms); - assert_eq!(seams.len(), 1, "{seams:?}"); - let seam = &seams[0]; + let fills = seam_fills(&res.paths, ¶ms, (24, 16)).unwrap(); + assert_eq!(fills.strokes.len(), 1, "{fills:?}"); + let seam = &fills.strokes[0]; assert_eq!((seam.color, seam.stroke), (res.paths[0].color, Some(SEAM_WIDTH))); // Every piece of the stroke is a piece of both paths, and it runs from the image's top to // its bottom along the edge, not along the image's border. @@ -253,25 +315,28 @@ mod tests { } let ys: Vec = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect(); assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0)); + // The clip is the image's box. + let corners: Vec<(f64, f64)> = fills.clip.subpaths.iter().flat_map(points).collect(); + assert_eq!(corners, [(0.0, 0.0), (24.0, 0.0), (24.0, 16.0), (0.0, 16.0)]); } #[test] fn only_abutting_fills_get_seam_strokes() { - let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params); + let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params, (img.width, img.height)); let img = two_colors(); - assert_eq!(seams(&img, &color(Method::Overlapping)), []); - assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), []); + assert_eq!(seams(&img, &color(Method::Overlapping)), None); + assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), None); // Flat Logo's shapes are stacked, whatever the method says. let abutting = trace(&img, &color(Method::Abutting)); - assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }), []); - // A color left out leaves no neighbour: a dark bar on white, with Ignore White. + assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }, (24, 16)), None); + // A color left out leaves no neighbor: a dark bar on white, with Ignore White. let bar = Raster::from_fn(24, 16, |x, _| if (8..16).contains(&x) { [0, 0, 0, 255] } else { [255; 4] }); let bw = TraceParams { mode: Mode::BlackAndWhite, method: Method::Abutting, ignore_white: true, ..TraceParams::default() }; let res = trace(&bar, &bw); assert_eq!(res.paths.len(), 1, "{res:?}"); - assert_eq!(seam_fills(&res.paths, &bw), []); + assert_eq!(seam_fills(&res.paths, &bw, (24, 16)), None); // Both colors traced, the bar's two sides are shared. - let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }); - assert_eq!(both.iter().map(|s| s.path.subpaths.len()).sum::(), 2, "{both:?}"); + let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }).unwrap(); + assert_eq!(both.strokes.iter().map(|s| s.path.subpaths.len()).sum::(), 2, "{both:?}"); } } diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index bfbcf0d5b3..b5dfb3eee0 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths and Convert to Parametric Shape; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and @@ -11,6 +11,7 @@ pub mod dashes; pub mod set_corners; pub mod shape; pub mod shared_edge; +pub mod tangent_circle; use egui::Ui; use serde_json::{Map, Value, json}; @@ -70,6 +71,7 @@ pub fn menu() -> Vec { Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), + Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs new file mode 100644 index 0000000000..29dc4f45d4 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs @@ -0,0 +1,161 @@ +//! Tangent Circle in the interface: its dialog (the radius, with two shapes selected, and which +//! circle to draw, or all), which previews the circles on the canvas and runs +//! `addon.pathtools.tangentCircle` on OK. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.tangentCircle"; +pub const KIND: &str = "tangentCircle"; +/// The radius the command takes (pt). +const RADII: std::ops::RangeInclusive = 0.01..=1e6; +/// The most circles the command lists. +const MAX_CIRCLES: u64 = 64; +const LABEL_W: f32 = 60.0; +const FIELD_W: f32 = 90.0; +/// How many circles the last preview found (a private field). +const FOUND: &str = "__found"; +/// The parameters the last preview ran with (a private field). +const TRIED: &str = "__tried"; + +/// How many objects were selected when the dialog opened (a private field): two take a radius, +/// three set it themselves. The preview selects the circles it draws, so the count is kept. +const SHAPES: &str = "__shapes"; + +/// The dialog's fields to start with: a radius of 36 pt, every circle, Preview on (the Circle menu +/// lists the circles the last preview found), and the selection's size. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + let shapes = app.session.active().map_or(0, |st| st.selection.objects.len()); + json!({ "radius": 36, "circle": 0, "preview": true, SHAPES: shapes }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Tangent Circle").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +fn shapes(d: &Dialog) -> u64 { + d.fields.get(SHAPES).and_then(Value::as_u64).unwrap_or(0) +} + +/// The command's parameters: the radius only with two shapes. +fn params(d: &Dialog) -> Value { + let mut p = json!({ "circle": d.fields.get("circle").cloned().unwrap_or(json!(0)) }); + if shapes(d) == 2 + && let (Some(o), Some(r)) = (p.as_object_mut(), d.fields.get("radius")) + { + o.insert("radius".into(), r.clone()); + } + p +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + ui.add_enabled_ui(shapes(d) == 2, |ui| form::length_within(ui, d, "radius", unit, FIELD_W, Some(RADII))); + }); + // The command lists at most 64 circles; the menu never holds more. + let found = d.fields.get(FOUND).and_then(Value::as_u64).unwrap_or(0).min(MAX_CIRCLES); + let pick = d.fields.get("circle").and_then(Value::as_u64).unwrap_or(0).min(MAX_CIRCLES); + let mut options = vec![tl!("All").to_string()]; + options.extend((1..=found.max(pick)).map(|n| n.to_string())); + let names: Vec<&str> = options.iter().map(String::as_str).collect(); + let current = options.get(usize::try_from(pick).unwrap_or(0)).cloned().unwrap_or_default(); + widgets::label_row(ui, tl!("Circle:"), LABEL_W, |ui| { + if let Some(i) = widgets::dropdown_names(ui, "tangent-circle-pick", ¤t, &names, FIELD_W) { + d.fields.insert("circle".into(), json!(i)); + } + }); + let p = params(d); + let fresh = d.fields.get(TRIED) != Some(&p); + match form::preview_result(app, ui, d, "Tangent Circle", COMMAND, p.clone()) { + Some(r) => { + d.fields.insert(FOUND.into(), r["found"].clone()); + } + // A new radius or pick found nothing: the menu no longer lists the earlier circles, and a + // pick past the circles left shows them all again. + None if fresh && d.bool("preview") => { + d.fields.insert(FOUND.into(), json!(0)); + if pick > 0 { + d.fields.insert("circle".into(), json!(0)); + } + } + None => {} + } + d.fields.insert(TRIED.into(), p); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + fn circle(app: &mut VectorcraftApp, cx: f64, cy: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + } + + #[test] + fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 100.0, 10.0); + let b = circle(&mut app, 130.0, 100.0, 10.0); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Tangent Circle…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Tangent Circle", "Radius:", "Circle:", "All", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len(); + // Preview is on from the start: radius 36 gives eight circles, and the menu lists them. + assert_eq!(count(&app), 10, "previewed on opening: {}", app.ui.status); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(8)); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("radius".into(), json!(20)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + // Six circles of radius 20 touch both: all previewed. + assert_eq!(count(&app), 8, "previewed: {}", app.ui.status); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(6)); + app.ui.dialog.as_mut().unwrap().fields.insert("circle".into(), json!(2)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), 3, "one previewed"); + // A pick past the circles found (a control request can set any number) goes back to All. + app.ui.dialog.as_mut().unwrap().fields.insert("circle".into(), json!(u64::MAX)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["circle"], json!(0)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(6)); + // Radius 2 cannot reach across the 10 pt gap: the menu lists no circles. + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(2)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__found"], json!(0), "{}", app.ui.status); + crate::dialogs::cancel(&mut app); + assert_eq!(count(&app), 2, "rolled back"); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(5)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + // Radius 5: the one circle in the gap. + assert_eq!(count(&app), 3); + } +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 139d0adc7d..613b0fae9c 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -395,20 +395,76 @@ struct SharedKey { /// The painter's clip: the lines of the path outside it have no triangles in the mesh. clip: egui::Rect, stroke: Stroke, + /// Where the dash pattern starts along the path, in document units, when it is dashed. + dash: Option, pixels_per_point: f32, tessellation: TessellationOptions, } +/// The length of a dash of a dashed overlay, in screen pixels. +const DASH: f32 = 4.0; +/// The length of the gap after each dash of a dashed overlay, in screen pixels. +const GAP: f32 = 3.0; + +/// Add to `out` the dashes of `line` drawn with `s`, [`DASH`] pixels drawn and [`GAP`] left out, +/// with the pattern started `from` pixels along it: from 0, the dashes [`Shape::dashed_line`] gives. +pub(super) fn dashes_from(line: &[Pos2], s: Stroke, from: f64, out: &mut Vec) { + let period = f64::from(DASH + GAP); + let phase = from.rem_euclid(period); + let phase = if phase.is_finite() { phase as f32 } else { 0.0 }; + if line.len() < 2 { + return; + } + if phase >= DASH { + Shape::dashed_line_many_with_offset(line, s, &[DASH], &[GAP], DASH + GAP - phase, out); + return; + } + // The pattern starts within a dash: the rest of that dash is drawn, then the pattern goes on + // after its gap. + let mut left = DASH - phase; + for (i, w) in line.windows(2).enumerate() { + let len = (w[1] - w[0]).length(); + if len >= left { + let cut = w[0] + (w[1] - w[0]) * (left / len); + let mut dash = line[..=i].to_vec(); + dash.push(cut); + segments(&dash, s, out); + let mut rest = vec![cut]; + rest.extend_from_slice(&line[i + 1..]); + Shape::dashed_line_many_with_offset(&rest, s, &[DASH], &[GAP], GAP, out); + return; + } + left -= len; + } + segments(line, s, out); +} + +/// Add to `out` each line of `line` that has a length as its own [`Shape::LineSegment`], as +/// [`Shape::dashed_line`] draws a dash. +fn segments(line: &[Pos2], s: Stroke, out: &mut Vec) { + out.extend(line.windows(2).filter(|w| w[0] != w[1]).map(|w| Shape::line_segment([w[0], w[1]], s))); +} + impl SharedPaths { - /// The mesh that draws `path` with `s` at the view `xf` with the painter `p`: the one kept in - /// this frame or in `last` (the last frame's) when it was built for the same, else a new one. - /// It is kept for the next frame. - fn mesh(&mut self, last: &mut HashMap, path: &Arc, xf: &Xf, s: Stroke, p: &egui::Painter) -> Arc { + /// The mesh that draws `path` with `s`, dashed from `dash` document units along the pattern + /// when that is set, at the view `xf` with the painter `p`: the one kept in this frame or in + /// `last` (the last frame's) when it was built for the same, else a new one. It is kept for + /// the next frame. + fn mesh( + &mut self, + last: &mut HashMap, + path: &Arc, + xf: &Xf, + s: Stroke, + dash: Option, + p: &egui::Painter, + ) -> Arc { let ctx = p.ctx(); let key = SharedKey { view: xf.affine().as_coeffs(), clip: p.clip_rect(), stroke: s, + dash, pixels_per_point: ctx.pixels_per_point(), tessellation: ctx.tessellation_options(|o| *o), }; @@ -425,7 +481,16 @@ impl SharedPaths { tessellator.set_clip_rect(key.clip); let mut mesh = Mesh::default(); for line in to_screen_path(path, xf) { - tessellator.tessellate_shape(Shape::line(line, s), &mut mesh); + match dash { + Some(from) => { + let mut dashes = vec![]; + dashes_from(&line, s, from * xf.zoom, &mut dashes); + for d in dashes { + tessellator.tessellate_shape(d, &mut mesh); + } + } + None => tessellator.tessellate_shape(Shape::line(line, s), &mut mesh), + } } SharedMesh { path: Arc::clone(path), key, mesh: Arc::new(mesh) } } @@ -476,8 +541,8 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: stroke_path(p, path, xf, s); } } - Overlay::SharedPath { path, color, width } => { - let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), p); + Overlay::SharedPath { path, color, width, dash } => { + let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), *dash, p); if !mesh.is_empty() { p.add(Shape::mesh(mesh)); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0051ded2d3..9a5d7fc0b3 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -99,7 +99,8 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() { path.line_to((250.0, 160.0)); let a = std::sync::Arc::new(path.clone()); let b = std::sync::Arc::new(path.clone()); - let shared_of = |p: &std::sync::Arc| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0 }; + let shared_of = + |p: &std::sync::Arc| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0, dash: None }; let first = one(frame(&[shared_of(&a)], 1.0, &mut shared)); assert!(!first.vertices.is_empty()); let again = one(frame(&[shared_of(&a)], 1.0, &mut shared)); @@ -143,6 +144,71 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() { half.line_to((5100.0, 5000.0)); let half = one(frame(&[shared_of(&std::sync::Arc::new(half))], 1.0, &mut shared)); assert_eq!(*half, *first, "the subpath off the canvas adds no triangles"); + // A dashed shared path keeps its mesh too, and the place its dashes start is part of it. + let dashed_of = |p: &std::sync::Arc, dash: f64| Overlay::SharedPath { + path: std::sync::Arc::clone(p), + color: [0x80, 0x80, 0x80], + width: 1.0, + dash: Some(dash), + }; + let dashed = one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared)); + assert!(!dashed.vertices.is_empty() && *dashed != *first, "the dashes leave out parts of the line"); + assert!(std::sync::Arc::ptr_eq(&dashed, &one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared)))); + let moved = one(frame(&[dashed_of(&a, 2.0)], 1.0, &mut shared)); + assert!(!std::sync::Arc::ptr_eq(&dashed, &moved) && *dashed != *moved, "dashes that start elsewhere build a new mesh"); +} + +/// A line drawn dashed in pieces, each piece's dashes starting as far along the pattern as the +/// pieces before it are long, shows the dashes the whole line shows dashed in one go, whether a +/// piece starts within a dash or within a gap, and a pattern started at 0 gives the dashes of +/// [`Shape::dashed_line`]. +#[test] +fn a_line_dashed_in_pieces_dashes_as_the_whole_line_does() { + // The stretches of x that dashes along the x axis cover, with touching ones joined. + let covered = |shapes: &[Shape]| -> Vec<(f32, f32)> { + let mut spans: Vec<(f32, f32)> = shapes + .iter() + .map(|s| { + let xs: Vec = match s { + Shape::LineSegment { points, .. } => points.iter().map(|p| p.x).collect(), + Shape::Path(p) => p.points.iter().map(|p| p.x).collect(), + other => panic!("{other:?}"), + }; + (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max)) + }) + .collect(); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut joined: Vec<(f32, f32)> = vec![]; + for (a, b) in spans { + match joined.last_mut() { + Some(last) if a - last.1 < 1e-3 => last.1 = last.1.max(b), + _ => joined.push((a, b)), + } + } + joined + }; + let s = Stroke::new(1.0, Color32::WHITE); + let along = |xs: &[f32]| -> Vec { xs.iter().map(|&x| pos2(x, 10.0)).collect() }; + let whole = along(&[0.0, 30.0, 61.5, 100.0]); + let mut one_go = vec![]; + overlays::dashes_from(&whole, s, 0.0, &mut one_go); + assert_eq!(covered(&one_go), covered(&Shape::dashed_line(&whole, s, 4.0, 3.0))); + // Cuts at 50 (within a dash: 50 is 1 past the dash that starts at 49) and at 75 (within a gap). + let mut pieces = vec![]; + overlays::dashes_from(&along(&[0.0, 30.0, 50.0]), s, 0.0, &mut pieces); + overlays::dashes_from(&along(&[50.0, 61.5, 75.0]), s, 50.0, &mut pieces); + overlays::dashes_from(&along(&[75.0, 100.0]), s, 75.0, &mut pieces); + let (want, got) = (covered(&one_go), covered(&pieces)); + assert_eq!(want.len(), got.len(), "{want:?} {got:?}"); + assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-3 && (w.1 - g.1).abs() < 1e-3), "{want:?} {got:?}"); + // Every dash is drawn as line segments with a length, as `Shape::dashed_line` draws them: the + // cut first dash, a dash cut on a vertex (at 4) and a line shorter than the rest of a dash too. + let mut ends = vec![]; + overlays::dashes_from(&along(&[0.0, 4.0, 10.0]), s, 0.0, &mut ends); + overlays::dashes_from(&along(&[0.0, 1.0, 2.0]), s, 1.0, &mut ends); + for shape in one_go.iter().chain(&pieces).chain(&ends) { + assert!(matches!(shape, Shape::LineSegment { points: [a, b], .. } if a != b), "{shape:?}"); + } } #[test] diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index d4a7c7f0e8..f1c63eafb4 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -3292,7 +3292,7 @@ fn the_control_bar_s_controls_stay_inside_the_bar_in_a_narrow_window() { wide(&mut app, "an embedded image", &["Unembed…", "Image Trace", "Mask", "Crop Image", "Remove Background"]); app.select_tool(vectorcraft_tools::cropimage::ID); check(&mut app, "Crop Image"); - wide(&mut app, "Crop Image", &["X:", "Y:", "W:"]); + wide(&mut app, "Crop Image", &["PPI", "X:", "Y:", "W:", "H:"]); app.select_tool("selection"); app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); let trace = selected(&app); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index fab55b8986..da1062838f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -472,6 +472,7 @@ registry! { RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC, SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, @@ -653,12 +654,16 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields /// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. +/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value +/// Composite Fonts' Show Sample can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); return Ok(()); } + if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { + return composite_fonts::field_set(d, field); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs index 5f0bb8693e..efba47da86 100644 --- a/crates/ui-egui/src/dialogs/check_spelling.rs +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -11,10 +11,20 @@ //! - `change_to`: the replacement word (from suggestions or typed) //! - `node_id`, `start`, `end`, `lang`: location of the current misspelling //! - `ids`: object IDs checked (None: entire document) -//! - `skipped`: list of `[node_id, start]` skipped by Ignore +//! - `skipped`: list of `[node_id, start, word]` skipped by Ignore, which Change All leaves alone +//! - `queue`: the words the last check listed after the one shown, last first; `queue_more` +//! whether that check had more, and `queue_from` (`[node_id, byte]`) where the next check goes +//! on from +//! - `revision`: `[document revision, custom dictionary generation]` as of the word shown; when +//! either has moved, the next step checks the scope again from its start //! - `done`: whether spell checking has finished (or no unrecognized words found) +//! +//! Ignore and Ignore All take the next word from `queue`, and a new check (`text.spelling.check`'s +//! `from`) goes on from `queue_from` once it is empty, through the rest of that type object and +//! then the objects after it, so every word is reached however many come before it. Change All +//! looks through the whole scope, one check after another, before it changes anything. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use serde_json::{Value, json}; @@ -56,30 +66,22 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if app.session.active().is_none() { return Err("no document".into()); } - let doc_uid = app.session.doc().map_err(|e| e.to_string())?.uid; - let (ids, remaining_ids): (Option>, Vec) = { + let (doc_uid, ids) = { let st = app.session.doc().map_err(|e| e.to_string())?; - let selected = &st.selection.objects; - if !selected.is_empty() { - let selected_ids: Vec = selected.iter().map(|n| n.0).collect(); - (Some(selected_ids.clone()), selected_ids) - } else { - let mut all_ordered = Vec::new(); - st.doc.walk(|n| { - if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { - all_ordered.push(n.id.0); - } - }); - (None, all_ordered) - } + // The selection (groups too: the check goes through the type inside them), or, with + // nothing selected, every visible, unlocked type object (the check's default). + let selected: Vec = st.selection.objects.iter().map(|n| n.0).collect(); + (st.uid, (!selected.is_empty()).then_some(selected)) }; let mut d = Dialog::new( KIND, json!({ "doc_uid": doc_uid, "ids": ids, - "remaining_ids": remaining_ids, "skipped": [], + "queue": [], + "queue_more": false, + "queue_from": null, "not_in_dictionary": "", "context": "", "context_before": "", @@ -95,31 +97,69 @@ pub fn open(app: &mut VectorcraftApp) -> Result { "done": false, }), ); - advance(app, &mut d)?; + advance(app, &mut d, None, 1)?; app.ui.dialog = Some(d); Ok(Value::Null) } -fn get_skipped(d: &Dialog) -> Vec<(u64, u64)> { +/// An occurrence Ignore skipped: (id, start, word). The word is kept with its bytes, so after +/// another command moves the text, a different word that now starts there is not skipped. +type Skip = (u64, u64, String); + +fn get_skipped(d: &Dialog) -> BTreeSet { d.fields .get("skipped") .and_then(Value::as_array) .map(|arr| { arr.iter() - .filter_map(|pair| { - let a = pair.as_array()?; - if a.len() == 2 { Some((a[0].as_u64()?, a[1].as_u64()?)) } else { None } + .filter_map(|s| match s.as_array().map(Vec::as_slice) { + Some([id, start, word]) => Some((id.as_u64()?, start.as_u64()?, word.as_str()?.to_string())), + _ => None, }) .collect() }) .unwrap_or_default() } -fn set_skipped(d: &mut Dialog, skipped: &[(u64, u64)]) { - let arr: Vec = skipped.iter().map(|&(id, start)| json!([id, start])).collect(); +fn set_skipped(d: &mut Dialog, skipped: &BTreeSet) { + let arr: Vec = skipped.iter().map(|(id, start, word)| json!([id, start, word])).collect(); d.fields.insert("skipped".into(), json!(arr)); } +/// Whether Ignore skipped this occurrence of a word. +fn is_skipped(skipped: &BTreeSet, w: &Word) -> bool { + skipped.contains(&(w.0, w.1 as u64, w.3.clone())) +} + +/// Moves the Ignore positions in `id` that come after edits there by what each edit changed in +/// length: `edits` are the (start, end) bytes each replaced with `new_len` bytes. +fn shift_skipped(d: &mut Dialog, id: u64, edits: &[(usize, usize)], new_len: usize) { + let skipped = get_skipped(d) + .into_iter() + .map(|(sid, start, word)| if sid == id { (sid, shifted(start as usize, edits, new_len) as u64, word) } else { (sid, start, word) }) + .collect(); + set_skipped(d, &skipped); +} + +/// Where byte `at` of a text ends up after `edits` ((start, end) bytes, none of them overlapping +/// `at`) are each replaced with `new_len` bytes. +fn shifted(at: usize, edits: &[(usize, usize)], new_len: usize) -> usize { + edits.iter().filter(|(_, end)| *end <= at).fold(at, |at, (start, end)| (at + new_len).saturating_sub(end - start)) +} + +/// Most unknown words one check lists when the dialog reads on through the scope (Ignore once +/// the queue is empty, a check started again, Change All): the check's own limit, or a smaller +/// one in tests. +#[cfg(not(test))] +fn page() -> usize { + vectorcraft_engine::cmd::spelling::MAX_WORDS +} + +#[cfg(test)] +fn page() -> usize { + tests::PAGE.with(std::cell::Cell::get) +} + /// Extracts the sentence containing `range` within `text`, returning (before, word, after). pub fn extract_sentence_context(text: &str, range: Range) -> (String, String, String) { let empty = (String::new(), String::new(), String::new()); @@ -210,105 +250,214 @@ fn set_done(d: &mut Dialog) { d.fields.insert("lang".into(), Value::Null); } -/// Advance to the next unrecognized word or complete the spell check. -pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - let mut remaining_ids: Vec = - d.fields.get("remaining_ids").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); +/// One unknown word: (id, start, end, word, lang). +type Word = (u64, usize, usize, String, String); - if remaining_ids.is_empty() && d.fields.get("ids").is_none_or(Value::is_null) { - let st = app.session.doc().map_err(|e| e.to_string())?; - st.doc.walk(|n| { - if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { - remaining_ids.push(n.id.0); - } - }); - d.fields.insert("remaining_ids".into(), json!(remaining_ids)); +/// One word of a `text.spelling.check` result. +fn word_at(w: &Value) -> Option { + let id = w.get("id")?.as_u64()?; + let start = usize::try_from(w.get("start")?.as_u64()?).ok()?; + let end = usize::try_from(w.get("end")?.as_u64()?).ok()?; + let word = w.get("word")?.as_str()?.to_string(); + let lang = w.get("lang").and_then(Value::as_str).unwrap_or("en").to_string(); + Some((id, start, end, word, lang)) +} + +/// One word of `queue`, kept as `[id, start, end, word, lang]`. +fn queued_word(w: &Value) -> Option { + match w.as_array().map(Vec::as_slice) { + Some([id, start, end, word, lang]) => Some(( + id.as_u64()?, + usize::try_from(start.as_u64()?).ok()?, + usize::try_from(end.as_u64()?).ok()?, + word.as_str()?.to_string(), + lang.as_str()?.to_string(), + )), + _ => None, } +} +/// The check's params for the dialog's scope, going on from `from` ((id, byte)) when given. A +/// selected object that another command deleted is left out, so the rest of the selection is still +/// checked; with every one deleted, the list is empty and the check finds nothing (not the whole +/// document, which `ids` left out would check). +fn check_params(app: &VectorcraftApp, d: &Dialog, from: Option<(u64, usize)>, max: usize) -> Value { + let ids = match d.fields.get("ids") { + Some(Value::Array(ids)) => { + let exists = + |id: &Value| id.as_u64().is_some_and(|id| app.session.doc().is_ok_and(|st| st.doc.node(vectorcraft_doc::NodeId(id)).is_some())); + Value::Array(ids.iter().filter(|id| exists(id)).cloned().collect()) + } + _ => Value::Null, + }; + match from { + Some((id, byte)) => json!({ "ids": ids, "from": { "id": id, "byte": byte }, "max": max }), + None => json!({ "ids": ids, "max": max }), + } +} + +/// Checks from `from` ((id, byte); the start of the scope when None), listing at most `max` +/// words, and shows the first one Ignore did not skip, keeping the rest in `queue`; completes the +/// spell check when there is none. Past a check whose words were all skipped it lists [`page`] +/// words at a time. +pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog, mut from: Option<(u64, usize)>, mut max: usize) -> Result<(), String> { let skipped = get_skipped(d); - loop { - if remaining_ids.is_empty() { - set_done(d); - return Ok(()); - } - - let check_res = app.run("text.spelling.check", json!({ "ids": remaining_ids })).map_err(|e| e.to_string())?; - let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); + let params = check_params(app, d, from, max); + let check_res = match app.run("text.spelling.check", params) { + Ok(r) => r, + // The object `from` names left the scope (another command hid, locked or deleted + // it): start the scope again, where every word before is now right or skipped. + Err(_) if from.is_some() => { + from = None; + max = page(); + continue; + } + Err(e) => return Err(e.to_string()), + }; + let words: Vec = check_res.get("words").and_then(Value::as_array).map(|a| a.iter().filter_map(word_at).collect()).unwrap_or_default(); let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); - - let next_word = words - .iter() - .find(|w| { - let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); - let start = w.get("start").and_then(Value::as_u64).unwrap_or(0); - !skipped.contains(&(id, start)) - }) - .cloned(); - - if let Some(w) = next_word { - let id = w["id"].as_u64().unwrap_or(0); - let start = w["start"].as_u64().unwrap_or(0) as usize; - let end = w["end"].as_u64().unwrap_or(0) as usize; - let word = w["word"].as_str().unwrap_or("").to_string(); - let lang = w["lang"].as_str().unwrap_or("en").to_string(); - - let (before, target, after) = { - let st = app.session.doc().map_err(|e| e.to_string())?; - if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { - extract_sentence_context(&t.plain_text(), start..end) - } else { - (String::new(), word.clone(), String::new()) - } - }; - - let sugg_res = app.run("text.spelling.suggest", json!({ "word": word, "lang": lang, "max": 10 })).map_err(|e| e.to_string())?; - let suggestions: Vec = sugg_res - .get("suggestions") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) - .unwrap_or_default(); - - let change_to = suggestions.first().cloned().unwrap_or_else(|| word.clone()); - let full_context = format!("{before}{target}{after}"); - - d.fields.insert("not_in_dictionary".into(), json!(word)); - d.fields.insert("context".into(), json!(full_context)); - d.fields.insert("context_before".into(), json!(before)); - d.fields.insert("context_word".into(), json!(target)); - d.fields.insert("context_after".into(), json!(after)); - d.fields.insert("suggestions".into(), json!(suggestions)); - d.fields.insert("selected_suggestion".into(), json!(suggestions.first().cloned())); - d.fields.insert("change_to".into(), json!(change_to)); - d.fields.insert("node_id".into(), json!(id)); - d.fields.insert("start".into(), json!(start)); - d.fields.insert("end".into(), json!(end)); - d.fields.insert("lang".into(), json!(lang)); - d.fields.insert("done".into(), json!(false)); - return Ok(()); + let next_from = words.last().map(|w| (w.0, w.2)); + let mut rest = words.into_iter().filter(|w| !is_skipped(&skipped, w)); + if let Some(w) = rest.next() { + let mut queue: Vec = rest.map(|(id, start, end, word, lang)| json!([id, start, end, word, lang])).collect(); + queue.reverse(); + d.fields.insert("queue".into(), Value::Array(queue)); + d.fields.insert("queue_more".into(), json!(more)); + d.fields.insert("queue_from".into(), json!(next_from.map(|(id, byte)| [id, byte as u64]))); + return show(app, d, w); } - - if more && !words.is_empty() { - let last_id = words.last().and_then(|w| w.get("id")).and_then(Value::as_u64).unwrap_or(0); - if let Some(pos) = remaining_ids.iter().position(|&id| id == last_id) - && pos > 0 - { - remaining_ids.drain(0..pos); - d.fields.insert("remaining_ids".into(), json!(remaining_ids)); - continue; + match next_from { + Some(f) if more => { + from = Some(f); + max = page(); } - if remaining_ids.len() > 1 { - remaining_ids.remove(0); - d.fields.insert("remaining_ids".into(), json!(remaining_ids)); - continue; + _ => { + set_done(d); + return Ok(()); } } - - set_done(d); - return Ok(()); } } +/// Shows the next word of `queue` that Ignore did not skip and Ignore All did not add, or goes on +/// with a new check from `queue_from` when the queue runs out. The queue holds what a check listed +/// at the document revision of the word shown, so callers use it only while [`resume_at`] gives +/// Some. +fn step(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let skipped = get_skipped(d); + loop { + let next = d.fields.get_mut("queue").and_then(Value::as_array_mut).and_then(Vec::pop); + let Some(next) = next else { break }; + let Some(w) = queued_word(&next) else { continue }; + if is_skipped(&skipped, &w) || ignored_all(app, &w.3) { + continue; + } + return show(app, d, w); + } + let from = d.fields.get("queue_from").and_then(Value::as_array).and_then(|a| match a.as_slice() { + [id, byte] => Some((id.as_u64()?, usize::try_from(byte.as_u64()?).ok()?)), + _ => None, + }); + match from { + Some(from) if d.bool("queue_more") => advance(app, d, Some(from), page()), + _ => { + set_done(d); + Ok(()) + } + } +} + +/// Whether the active document's check skips `word` (Ignore All). +fn ignored_all(app: &VectorcraftApp, word: &str) -> bool { + let Some(w) = vectorcraft_engine::cmd::spelling::custom_word(word) else { return false }; + app.session.doc().is_ok_and(|st| st.spelling_ignored.contains(&w)) +} + +/// Shows `w` with its sentence and suggestions. +fn show(app: &mut VectorcraftApp, d: &mut Dialog, w: Word) -> Result<(), String> { + let (id, start, end, word, lang) = w; + let (before, target, after) = { + let st = app.session.doc().map_err(|e| e.to_string())?; + if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { + extract_sentence_context(&t.plain_text(), start..end) + } else { + (String::new(), word.clone(), String::new()) + } + }; + + let sugg_res = app.run("text.spelling.suggest", json!({ "word": word, "lang": lang, "max": 10 })).map_err(|e| e.to_string())?; + let suggestions: Vec = sugg_res + .get("suggestions") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) + .unwrap_or_default(); + + let change_to = suggestions.first().cloned().unwrap_or_else(|| word.clone()); + let full_context = format!("{before}{target}{after}"); + + d.fields.insert("not_in_dictionary".into(), json!(word)); + d.fields.insert("context".into(), json!(full_context)); + d.fields.insert("context_before".into(), json!(before)); + d.fields.insert("context_word".into(), json!(target)); + d.fields.insert("context_after".into(), json!(after)); + d.fields.insert("suggestions".into(), json!(suggestions)); + d.fields.insert("selected_suggestion".into(), json!(suggestions.first().cloned())); + d.fields.insert("change_to".into(), json!(change_to)); + d.fields.insert("node_id".into(), json!(id)); + d.fields.insert("start".into(), json!(start)); + d.fields.insert("end".into(), json!(end)); + d.fields.insert("lang".into(), json!(lang)); + d.fields.insert("done".into(), json!(false)); + remember_revision(app, d); + Ok(()) +} + +/// Notes the document's revision and the custom dictionary's generation as of the word shown, +/// which [`resume_at`] compares. +fn remember_revision(app: &VectorcraftApp, d: &mut Dialog) { + d.fields.insert("revision".into(), json!(revision(app))); +} + +/// The document's revision and the custom dictionary's generation: when either moves, the words +/// before the one shown may have changed. +fn revision(app: &VectorcraftApp) -> Option<[u64; 2]> { + let doc = app.session.doc().map(|st| st.revision).ok()?; + Some([doc, vectorcraft_engine::cmd::spelling::dictionary_generation()]) +} + +/// The word shown: (id, start, end). +fn current(d: &Dialog) -> Option<(u64, usize, usize)> { + let id = d.fields.get("node_id").and_then(Value::as_u64)?; + let start = usize::try_from(d.fields.get("start").and_then(Value::as_u64)?).ok()?; + let end = usize::try_from(d.fields.get("end").and_then(Value::as_u64)?).ok()?; + Some((id, start, end)) +} + +/// Where the next check goes on from: the start of the word shown. When another command changed +/// the document or the custom dictionary since the word was shown, the text before the word may +/// hold new unknown words, and `queue` may be out of date, so the check starts the scope again +/// (None); [`advance`] still skips the occurrences Ignore skipped. +fn resume_at(app: &VectorcraftApp, d: &Dialog) -> Option<(u64, usize)> { + let now = revision(app)?; + if d.fields.get("revision") != Some(&json!(now)) { + return None; + } + let (id, start, _, true) = shown_word(app, d)? else { return None }; + Some((id, start)) +} + +/// The word shown, (id, start, end), and whether its object still holds it at those bytes; None +/// when there is none or its object is no longer type. +fn shown_word(app: &VectorcraftApp, d: &Dialog) -> Option<(u64, usize, usize, bool)> { + let (id, start, end) = current(d)?; + let st = app.session.doc().ok()?; + let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) else { return None }; + let word = d.str("not_in_dictionary"); + let still_there = !word.is_empty() && t.plain_text().get(start..end).is_some_and(|w| w == word); + Some((id, start, end, still_there)) +} + fn check_doc_uid(app: &VectorcraftApp, d: &Dialog) -> Result<(), String> { let doc_uid = d.fields.get("doc_uid").and_then(Value::as_u64); let active_uid = app.session.active().map(|st| st.uid); @@ -323,12 +472,19 @@ fn ignore(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if d.bool("done") { return Ok(()); } - let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); - let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0); - let mut skipped = get_skipped(d); - skipped.push((id, start)); - set_skipped(d, &skipped); - advance(app, d) + let unchanged = resume_at(app, d).is_some(); + if let Some((id, start, _, true)) = shown_word(app, d) { + let mut skipped = get_skipped(d); + skipped.insert((id, start as u64, d.str("not_in_dictionary"))); + set_skipped(d, &skipped); + } + go_on(app, d, unchanged) +} + +/// On past the word shown: the next word of the queue while nothing changed since it was shown, +/// otherwise the scope checked again from its start. +fn go_on(app: &mut VectorcraftApp, d: &mut Dialog, unchanged: bool) -> Result<(), String> { + if unchanged { step(app, d) } else { advance(app, d, None, page()) } } fn ignore_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -336,11 +492,13 @@ fn ignore_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if d.bool("done") { return Ok(()); } + let unchanged = resume_at(app, d).is_some(); let word = d.str("not_in_dictionary"); if !word.is_empty() { app.run("text.spelling.ignoreAll", json!({ "word": word })).map_err(|e| e.to_string())?; } - advance(app, d) + // The queue's other occurrences of the word are passed over too. + go_on(app, d, unchanged) } fn change(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -348,29 +506,31 @@ fn change(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { if d.bool("done") { return Ok(()); } - let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); - let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; - let end = d.fields.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; - let expected_word = d.str("not_in_dictionary"); + let from = resume_at(app, d); let change_to = d.str("change_to"); - if !change_to.trim().is_empty() && id > 0 { - let text_matches = { - let st = app.session.doc().map_err(|e| e.to_string())?; - if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { - let plain = t.plain_text(); - plain.get(start..end).map(|s| s == expected_word).unwrap_or(false) - } else { - false - } - }; + // Changed only while the word is still at the bytes shown. + let Some((id, start, end, true)) = shown_word(app, d) else { return advance(app, d, None, page()) }; + if change_to.trim().is_empty() { + return recheck(app, d, from); + } + if change_to == d.str("not_in_dictionary") { + // Nothing to change, so no undo step: on past the word. + return go_on(app, d, from.is_some()); + } + app.run("text.editRange", json!({ "id": id, "start": start, "end": end, "insert": change_to })).map_err(|e| e.to_string())?; + shift_skipped(d, id, &[(start, end)], change_to.len()); + // On from the replacement, which is shown when the dictionaries don't know it either (or + // from the start of the scope, when the document changed under the dialog). + recheck(app, d, from) +} - if text_matches { - app.run("text.editRange", json!({ "id": id, "start": start, "end": end, "insert": change_to })).map_err(|e| e.to_string())?; - } else { - return advance(app, d); - } +/// A new check after a change: on from `from` until the next unknown word, or the scope from its +/// start when `from` is None. +fn recheck(app: &mut VectorcraftApp, d: &mut Dialog, from: Option<(u64, usize)>) -> Result<(), String> { + match from { + Some(from) => advance(app, d, Some(from), 1), + None => advance(app, d, None, page()), } - advance(app, d) } fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -380,120 +540,48 @@ fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { } let word = d.str("not_in_dictionary"); let change_to = d.str("change_to"); + let here = resume_at(app, d); if word.is_empty() || change_to.trim().is_empty() { - return advance(app, d); + return recheck(app, d, here); } - let initial_ids = d.fields.get("ids").cloned().unwrap_or(Value::Null); let skipped = get_skipped(d); - let mut undo_group_started = false; - let mut execute_changes = || -> Result<(), String> { - let mut replaced_spans: Vec<(u64, usize, usize)> = Vec::new(); - let mut all_commands = Vec::new(); - loop { - let check_res = app.run("text.spelling.check", json!({ "ids": initial_ids })).map_err(|e| e.to_string())?; - let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); - let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); - - let mut by_node: BTreeMap> = BTreeMap::new(); - let mut new_edits = 0; - for w in &words { - let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); - let start = w.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; - let end = w.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; - let w_str = w.get("word").and_then(Value::as_str).unwrap_or(""); - if skipped.contains(&(id, start as u64)) { - continue; - } - if replaced_spans.iter().any(|&(r_id, r_start, r_end)| r_id == id && start >= r_start && start < r_end) { - continue; - } - if w_str.eq_ignore_ascii_case(&word) { - by_node.entry(id).or_default().push((start, end)); - new_edits += 1; - } - } - - if new_edits == 0 { - break; - } - - let new_len = change_to.len() as isize; - for (r_id, r_start, r_end) in &mut replaced_spans { - if let Some(ranges) = by_node.get(r_id) { - let delta: isize = ranges.iter().filter(|(_, end)| *end <= *r_start).map(|(start, end)| new_len - (*end - *start) as isize).sum(); - *r_start = (*r_start as isize + delta).max(0) as usize; - *r_end = (*r_end as isize + delta).max(0) as usize; - } - } - for (&id, ranges) in &by_node { - for &(start, _) in ranges { - let delta: isize = ranges - .iter() - .filter(|(_, other_end)| *other_end <= start) - .map(|(other_start, other_end)| new_len - (*other_end - *other_start) as isize) - .sum(); - let post_start = (start as isize + delta).max(0) as usize; - let post_end = post_start + change_to.len(); - replaced_spans.push((id, post_start, post_end)); - } - } - - let mut batch_commands = Vec::new(); - for (id, mut ranges) in by_node { - ranges.sort_by_key(|a| std::cmp::Reverse(a.0)); - for (start, end) in ranges { - batch_commands.push(json!({ - "command": "text.editRange", - "params": { - "id": id, - "start": start, - "end": end, - "insert": change_to, - } - })); - } - } - - if !batch_commands.is_empty() { - if batch_commands.len() == 1 && !more && all_commands.is_empty() && !undo_group_started { - let cmd = &batch_commands[0]; - app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; - break; - } else if more { - if !undo_group_started { - app.run("edit.undoGroup.begin", json!({ "label": "Change All" })).map_err(|e| e.to_string())?; - undo_group_started = true; - } - app.run("command.batch", json!({ "label": "Change All", "commands": batch_commands })).map_err(|e| e.to_string())?; - continue; - } else { - all_commands.extend(batch_commands); - break; - } - } - - break; - } - - if !all_commands.is_empty() { - if all_commands.len() == 1 && !undo_group_started { - let cmd = &all_commands[0]; - app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; - } else { - app.run("command.batch", json!({ "label": "Change All", "commands": all_commands })).map_err(|e| e.to_string())?; + // Every occurrence in the scope, found before anything changes, so the bytes each check gives + // stay true: one check after another, each going on from the end of the last word listed, + // until none says `more`. + let mut by_node: BTreeMap> = BTreeMap::new(); + let mut from = None; + loop { + let params = check_params(app, d, from, page()); + let check_res = app.run("text.spelling.check", params).map_err(|e| e.to_string())?; + let words: Vec = check_res.get("words").and_then(Value::as_array).map(|a| a.iter().filter_map(word_at).collect()).unwrap_or_default(); + let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); + for w in &words { + // An occurrence that already reads as the replacement is left alone: no edit, no undo step. + if w.3.eq_ignore_ascii_case(&word) && w.3 != change_to && !is_skipped(&skipped, w) { + by_node.entry(w.0).or_default().push((w.1, w.2)); } } - Ok(()) - }; - - let res = execute_changes(); - if undo_group_started { - let cancel = res.is_err(); - let _ = app.run("edit.undoGroup.end", json!({ "cancel": cancel })); + match words.last() { + Some((id, _, end, _, _)) if more => from = Some((*id, *end)), + _ => break, + } } - res?; - advance(app, d) + + if by_node.is_empty() { + // Nothing to change: on past the word shown, as Change does. + return go_on(app, d, here.is_some()); + } + // Every edit in one command: one undo step, each object laid out once. + let words: Vec = + by_node.iter().flat_map(|(&id, ranges)| ranges.iter().map(move |&(start, end)| json!({ "id": id, "start": start, "end": end }))).collect(); + app.run("text.spelling.change", json!({ "to": change_to, "words": words })).map_err(|e| e.to_string())?; + for (&id, ranges) in &by_node { + shift_skipped(d, id, ranges, change_to.len()); + } + // On from the shown word's replacement, where it moved to. + let from = here.map(|(id, start)| (id, by_node.get(&id).map_or(start, |ranges| shifted(start, ranges, change_to.len())))); + recheck(app, d, from) } fn add_to_dictionary(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { @@ -501,11 +589,13 @@ fn add_to_dictionary(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), Str if d.bool("done") { return Ok(()); } + // The check takes the word as right from now on, so it goes on from where the word starts. + let from = resume_at(app, d); let word = d.str("not_in_dictionary"); if !word.is_empty() { app.run("text.spelling.addWord", json!({ "word": word })).map_err(|e| e.to_string())?; } - advance(app, d) + recheck(app, d, from) } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { @@ -690,6 +780,378 @@ mod tests { const WORD_A: &str = "zqvspella"; const WORD_B: &str = "zqvspellb"; const WORD_C: &str = "zqvspellc"; + /// Never added to the custom dictionary, which the whole process shares (unlike WORD_C). + const WORD_D: &str = "zqvspelld"; + + thread_local! { + /// The most words one Change All check lists in this test thread ([`super::change_all_page`]). + pub(super) static PAGE: std::cell::Cell = const { std::cell::Cell::new(vectorcraft_engine::cmd::spelling::MAX_WORDS) }; + } + + fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + } + + /// The word the dialog shows: (id, start, word). + fn shown(app: &VectorcraftApp) -> (u64, u64, String) { + let d = app.ui.dialog.as_ref().unwrap(); + (d.fields["node_id"].as_u64().unwrap(), d.fields["start"].as_u64().unwrap(), d.str("not_in_dictionary")) + } + + fn act(app: &mut VectorcraftApp, f: fn(&mut VectorcraftApp, &mut crate::state::Dialog) -> Result<(), String>) { + let mut d = app.ui.dialog.take().unwrap(); + f(app, &mut d).unwrap(); + app.ui.dialog = Some(d); + } + + #[test] + fn ignore_goes_on_through_the_rest_of_the_same_type_object() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_B} one {WORD_B} two {WORD_B}")); + let other = text(&mut app, 100.0, &format!("then {WORD_A}")); + app.run("select.none", json!({})).unwrap(); + super::open(&mut app).unwrap(); + // Each step asks for one word on from the last, so every occurrence in the object is shown + // in turn before the next object's. + let mut seen = vec![shown(&app)]; + for _ in 0..4 { + act(&mut app, super::ignore); + if !app.ui.dialog.as_ref().unwrap().bool("done") { + seen.push(shown(&app)); + } + } + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + let b = WORD_B.len() as u64; + let want = + vec![(id, 0, WORD_B.to_string()), (id, b + 5, WORD_B.to_string()), (id, 2 * b + 10, WORD_B.to_string()), (other, 5, WORD_A.to_string())]; + assert_eq!(seen, want); + } + + #[test] + fn ignore_and_change_all_reach_every_word_of_a_selected_groups_type() { + let mut app = app(); + let a = text(&mut app, 50.0, &format!("{WORD_B} {WORD_D} {WORD_B}")); + let b = text(&mut app, 100.0, &format!("{WORD_D} {WORD_B}")); + let outside = text(&mut app, 150.0, &format!("{WORD_B} outside")); + app.run("select.set", json!({ "ids": [a, b] })).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [group] })).unwrap(); + PAGE.with(|p| p.set(1)); + + super::open(&mut app).unwrap(); + let mut seen = vec![shown(&app)]; + for _ in 0..5 { + act(&mut app, super::ignore); + if !app.ui.dialog.as_ref().unwrap().bool("done") { + seen.push(shown(&app)); + } + } + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + let ids: Vec<(u64, String)> = seen.into_iter().map(|(id, _, w)| (id, w)).collect(); + let want = [(a, WORD_B), (a, WORD_D), (a, WORD_B), (b, WORD_D), (b, WORD_B)].map(|(id, w)| (id, w.to_string())); + assert_eq!(ids, want, "the group's descendants, one word at a time; not the object outside it"); + + // Change All goes through the group one listed word at a time too. + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert_eq!(plain(&app, a), format!("fixed {WORD_D} fixed")); + assert_eq!(plain(&app, b), format!("{WORD_D} fixed")); + assert_eq!(plain(&app, outside), format!("{WORD_B} outside"), "outside the selection"); + } + + #[test] + fn change_all_reaches_a_target_past_a_full_check_of_other_words() { + let mut app = app(); + // The second WORD_A comes after a whole check's worth of other unknown words. + PAGE.with(|p| p.set(2)); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_D} {WORD_A} {WORD_B} {WORD_A}")); + super::open(&mut app).unwrap(); + // Ignore the first WORD_A, then change all from the second. + act(&mut app, super::ignore); + act(&mut app, super::ignore); + act(&mut app, super::ignore); + assert_eq!(shown(&app).2, WORD_A); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert_eq!(plain(&app, id), format!("{WORD_A} {WORD_B} {WORD_D} fixed {WORD_B} fixed"), "the ignored one stays"); + // On from the replacement: the WORD_B after it. + assert_eq!(shown(&app).2, WORD_B); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(plain(&app, id), format!("{WORD_A} {WORD_B} {WORD_D} {WORD_A} {WORD_B} {WORD_A}"), "one undo step"); + } + + #[test] + fn change_all_reaches_a_target_past_the_checks_limit_in_one_object() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + // A target, then the most other words one check lists, then a second target, all in one + // type object. + let others = vec![WORD_B; MAX_WORDS].join(" "); + let id = text(&mut app, 50.0, &format!("{WORD_A} {others} {WORD_A}")); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (id, 0, WORD_A.to_string())); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert_eq!(plain(&app, id), format!("fixed {others} fixed")); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(plain(&app, id), format!("{WORD_A} {others} {WORD_A}"), "one undo step"); + } + + #[test] + fn text_changed_under_the_dialog_is_checked_again_from_its_start() { + // A word of its own: Add to Dictionary puts it in the custom dictionary the process shares. + const STALE: &str = "zqvstaleword"; + for f in [super::ignore, super::ignore_all, super::change, super::change_all, super::add_to_dictionary] { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("hello {STALE}")); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (id, 6, STALE.to_string())); + // Another command replaces the text with a shorter one: the shown bytes are gone. + app.run("text.editRange", json!({ "id": id, "start": 0, "end": 6 + STALE.len(), "insert": WORD_D })).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, f); + forget(&mut app, &[STALE]); + assert_eq!(plain(&app, id), WORD_D, "nothing is changed at stale bytes"); + assert_eq!(shown(&app), (id, 0, WORD_D.to_string()), "the object is checked again from its start"); + } + } + + #[test] + fn a_restarted_check_still_skips_the_ignored_occurrences() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_A}")); + super::open(&mut app).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 10, WORD_B.to_string())); + // Another command changes the word shown, so the next step checks the object from its start. + app.run("text.editRange", json!({ "id": id, "start": 10, "end": 10 + WORD_B.len(), "insert": WORD_D })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 10, WORD_D.to_string()), "the ignored first word is not shown again"); + } + + #[test] + fn an_unknown_word_brought_back_before_the_shown_one_is_shown_again() { + // Words of their own: Add to Dictionary puts one in the custom dictionary the process shares. + // FIRST has as many bytes as "different", so the second word stays at the bytes shown. + const FIRST: &str = "zqvbckone"; + const SECOND: &str = "zqvbacktwo"; + for f in [super::ignore, super::ignore_all, super::change, super::change_all, super::add_to_dictionary] { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{FIRST} {SECOND}")); + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("different")); + act(&mut app, super::change); + // Drawing the dialog leaves the document's revision alone, so the next step goes on + // from the word shown rather than starting again. + let ctx = context(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["revision"][0], json!(app.session.doc().unwrap().revision)); + assert_eq!(shown(&app), (id, 10, SECOND.to_string())); + // Another command (Undo) brings the first word back before the one shown. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(plain(&app, id), format!("{FIRST} {SECOND}")); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, f); + forget(&mut app, &[SECOND]); + assert_eq!(shown(&app), (id, 0, FIRST.to_string()), "the check starts again and finds it"); + } + } + + #[test] + fn a_word_taken_out_of_the_custom_dictionary_is_shown_again() { + // Words of their own: the custom dictionary is shared by the whole process. + const FIRST: &str = "zqvdictone"; + const SECOND: &str = "zqvdicttwo"; + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{FIRST} {SECOND}")); + super::open(&mut app).unwrap(); + act(&mut app, super::add_to_dictionary); + assert_eq!(shown(&app), (id, 11, SECOND.to_string())); + // Another command takes the first word out of the dictionary again. + app.run("text.spelling.removeWord", json!({ "word": FIRST })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 0, FIRST.to_string()), "the check starts again and finds it"); + } + + #[test] + fn a_shown_object_that_leaves_the_scope_starts_the_scope_again() { + let mut app = app(); + let first = text(&mut app, 50.0, &format!("{WORD_A} here")); + let second = text(&mut app, 100.0, &format!("{WORD_B} there")); + app.run("select.none", json!({})).unwrap(); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app).0, first); + app.run("object.lock", json!({ "ids": [first] })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (second, 0, WORD_B.to_string()), "on to the type still in the scope"); + } + + #[test] + fn a_selected_object_deleted_under_the_dialog_leaves_the_scope() { + let mut app = app(); + let first = text(&mut app, 50.0, &format!("{WORD_A} here")); + let second = text(&mut app, 100.0, &format!("{WORD_B} there")); + let outside = text(&mut app, 150.0, &format!("{WORD_C} elsewhere")); + app.run("select.set", json!({ "ids": [first, second] })).unwrap(); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app).0, first); + app.run("edit.clear", json!({ "ids": [first] })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (second, 0, WORD_B.to_string()), "on to the selected type that is left"); + app.run("edit.clear", json!({ "ids": [second] })).unwrap(); + act(&mut app, super::ignore); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.bool("done"), "nothing left in the selection: not the rest of the document ({outside})"); + } + + /// Marks the first `n` occurrences of WORD_B in `id` (each WORD_B and a space) as skipped by + /// Ignore, with the last of them shown. + fn ignored_b_words(app: &mut VectorcraftApp, id: u64, n: usize) { + let step = WORD_B.len() + 1; + let d = app.ui.dialog.as_mut().unwrap(); + let skipped: Vec<_> = (0..n).map(|i| json!([id, i * step, WORD_B])).collect(); + d.fields.insert("skipped".into(), json!(skipped)); + let last = (n - 1) * step; + for (k, v) in [("node_id", json!(id)), ("start", json!(last)), ("end", json!(last + WORD_B.len())), ("not_in_dictionary", json!(WORD_B))] { + d.fields.insert(k.into(), v); + } + } + + #[test] + fn ignore_reaches_the_last_of_more_unknown_words_than_one_check_lists() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + let id = text(&mut app, 50.0, &vec![WORD_B; MAX_WORDS + 1].join(" ")); + super::open(&mut app).unwrap(); + ignored_b_words(&mut app, id, MAX_WORDS); + // Another command changes the document, so the next step checks the scope from its start, + // where every word one check lists was skipped. + text(&mut app, 100.0, "hello"); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, (MAX_WORDS * (WORD_B.len() + 1)) as u64, WORD_B.to_string()), "the last occurrence"); + act(&mut app, super::ignore); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + } + + #[test] + fn ignore_and_change_all_reach_a_selected_groups_type_past_the_checks_limit() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + let a = text(&mut app, 50.0, &vec![WORD_B; MAX_WORDS].join(" ")); + let b = text(&mut app, 100.0, &format!("{WORD_A} end")); + let outside = text(&mut app, 150.0, &format!("{WORD_D} outside")); + app.run("select.set", json!({ "ids": [a, b] })).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [group] })).unwrap(); + super::open(&mut app).unwrap(); + ignored_b_words(&mut app, a, MAX_WORDS); + // An edit outside the group moves the document's revision: the group is checked again. + app.run("text.editRange", json!({ "id": outside, "start": 0, "end": 0, "insert": "the " })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (b, 0, WORD_A.to_string()), "the next object in the group"); + act(&mut app, super::ignore); + assert!(app.ui.dialog.as_ref().unwrap().bool("done"), "not the object outside the group"); + + // Change All: a target, then the most words one check lists, then a target in the next object. + app.run("text.editRange", json!({ "id": a, "start": 0, "end": 0, "insert": format!("{WORD_A} ") })).unwrap(); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (a, 0, WORD_A.to_string())); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + act(&mut app, super::change_all); + assert!(plain(&app, a).starts_with(&format!("fixed {WORD_B} "))); + assert_eq!(plain(&app, b), "fixed end"); + } + + #[test] + fn ignore_all_and_add_to_dictionary_go_on_past_each_check() { + PAGE.with(|p| p.set(2)); + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_A} {WORD_D} {WORD_A}")); + super::open(&mut app).unwrap(); + assert_eq!(shown(&app), (id, 0, WORD_A.to_string())); + act(&mut app, super::ignore_all); + let mut seen = vec![shown(&app)]; + act(&mut app, super::ignore); + seen.push(shown(&app)); + act(&mut app, super::ignore); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + assert_eq!(seen, vec![(id, 10, WORD_B.to_string()), (id, 30, WORD_D.to_string())], "no WORD_A after Ignore All"); + + // Words of their own: the custom dictionary is shared by the whole process. + const ADDED: &str = "zqvaddone"; + const OTHER: &str = "zqvaddtwo"; + PAGE.with(|p| p.set(1)); + let mut app = super::tests::app(); + let id = text(&mut app, 50.0, &format!("{ADDED} {OTHER} {ADDED} {OTHER}")); + super::open(&mut app).unwrap(); + act(&mut app, super::add_to_dictionary); + let mut seen = vec![shown(&app)]; + act(&mut app, super::ignore); + seen.push(shown(&app)); + act(&mut app, super::ignore); + let done = app.ui.dialog.as_ref().unwrap().bool("done"); + forget(&mut app, &[ADDED]); + assert!(done); + assert_eq!(seen, vec![(id, 10, OTHER.to_string()), (id, 30, OTHER.to_string())]); + } + + #[test] + fn change_to_the_same_word_changes_nothing_and_goes_on() { + for f in [super::change, super::change_all] { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_D} and {WORD_D} {WORD_A}")); + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!(WORD_D)); + let depth = app.session.doc().unwrap().history.undo.len(); + act(&mut app, f); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth, "no undo step"); + assert_eq!(plain(&app, id), format!("{WORD_D} and {WORD_D} {WORD_A}")); + let d = WORD_D.len() as u64; + assert_eq!(shown(&app), (id, d + 5, WORD_D.to_string()), "on past the word shown"); + } + } + + #[test] + fn a_word_moved_by_another_command_is_not_taken_for_an_ignored_one() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("{WORD_A} {WORD_B} {WORD_A}")); + super::open(&mut app).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 10, WORD_B.to_string())); + // Another command puts a different unknown word where the ignored one was. + let len = plain(&app, id).len(); + app.run("text.editRange", json!({ "id": id, "start": 0, "end": len, "insert": format!("{WORD_D} {WORD_A} {WORD_B}") })).unwrap(); + act(&mut app, super::ignore); + assert_eq!(shown(&app), (id, 0, WORD_D.to_string()), "the word now at the ignored bytes is shown"); + } + + #[test] + fn change_all_changes_a_whole_checks_worth_of_occurrences_in_one_edit() { + use vectorcraft_engine::cmd::spelling::MAX_WORDS; + let mut app = app(); + let id = text(&mut app, 50.0, &vec![WORD_A; MAX_WORDS + 1].join(" ")); + super::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + let depth = app.session.doc().unwrap().history.undo.len(); + act(&mut app, super::change_all); + assert_eq!(plain(&app, id), vec!["fixed"; MAX_WORDS + 1].join(" ")); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + } + + #[test] + fn ignore_positions_move_with_the_edits_before_them() { + // "ab cd ef": cd (3..5) replaced with "wxyz" moves byte 6 to 8; byte 0 stays. + assert_eq!(super::shifted(6, &[(3, 5)], 4), 8); + assert_eq!(super::shifted(0, &[(3, 5)], 4), 0); + assert_eq!(super::shifted(9, &[(0, 2), (3, 5)], 1), 7); + } fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); @@ -1066,12 +1528,13 @@ mod tests { app.run("select.set", json!({ "ids": [] })).unwrap(); super::open(&mut app).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("not_in_dictionary"), WORD_A); + let ctx = context(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_A); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["node_id"], json!(editable_id)); - let rem = d.fields.get("remaining_ids").and_then(serde_json::Value::as_array).unwrap(); - assert!(rem.iter().any(|v| v.as_u64() == Some(editable_id))); - assert!(!rem.iter().any(|v| v.as_u64() == Some(locked_id))); + // The locked object's word is never shown. + click(&mut app, &ctx, "Ignore"); + assert!(app.ui.dialog.as_ref().unwrap().bool("done"), "locked type {locked_id} is left out"); } #[test] diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 6e3b6f84e1..41bef1f45b 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -5,14 +5,17 @@ //! out, Import… adds the fonts of a file and Export… writes the one picked to a file. Custom shows //! the custom character sets of the font picked: New adds a set based on the one picked, Delete Set //! takes it out, and Add puts the characters typed (Direct Entry) or the character of a Unicode code -//! into it; Delete takes the character picked out. Nothing changes in the document until OK, which +//! into it; Delete takes the character picked out. Show Sample draws a sample of the font picked +//! with lines that mark its metrics ([`sample`]). Nothing changes in the document until OK, which //! runs `type.compositeFonts.set` with every font as one undo step; Cancel leaves them as they were. //! //! Fields: `fonts` (the composite fonts as `type.compositeFonts.set` takes them), `selected` (the //! index of the one picked) and `name` (its name as typed); `custom` (whether the custom character //! sets show), `set` (the index of the set picked), `setName` (its name as typed), `entryMode` //! (`direct` or `unicode`), `entry` (the characters or code typed) and `char` (the index of the -//! character picked in the set). +//! character picked in the set); `sample` (whether the sample shows), `zoom` (its magnification in +//! percent) and `lineIcfBox`, `lineEmBox`, `lineBaseline`, `lineCapHeight`, `lineAscentDescent`, +//! `lineAscender` and `lineXHeight` (whether each of its lines shows). //! //! Behavior reference (public documentation): //! , @@ -29,6 +32,8 @@ use crate::picks::PickRequest; use crate::state::Dialog; use crate::{FilePick, VectorcraftApp, widgets}; +mod sample; + /// The dialog kind of Composite Fonts. pub const KIND: &str = "compositeFonts"; @@ -53,15 +58,22 @@ pub(super) const SPEC: DialogSpec = DialogSpec { }; /// Open Composite Fonts on the active document's composite fonts, the first one picked, with the -/// custom character sets hidden and nothing typed. +/// custom character sets and the sample hidden and nothing typed. pub fn open(app: &mut VectorcraftApp) -> Result { let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec(); let mut d = Dialog::new(KIND, json!({ "fonts": fonts, "selected": 0, "custom": false, "entryMode": "direct", "entry": "" })); + sample::defaults(&mut d.fields); show_selected(&mut d); app.ui.dialog = Some(d); Ok(Value::Null) } +/// Why `ui.dialog.set` can't set `field` of Composite Fonts `d` to the value it now holds (Show +/// Sample's fields, [`sample::check_field`]). +pub(super) fn field_set(d: &Dialog, field: &str) -> Result<(), String> { + sample::check_field(d, field) +} + /// The fonts the dialog holds. fn fonts(d: &Dialog) -> Vec { d.fields.get("fonts").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default() @@ -138,6 +150,8 @@ enum Action { Export, /// Custom: show or hide the custom character sets. Custom, + /// Show Sample or Hide Sample. + Sample, NewSet, DeleteSet, /// Add the characters typed, or the character of the code typed, to the set picked. @@ -178,6 +192,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Custom"), 64.0)).inner.clicked() { act = Some(Action::Custom); } + let label = if d.bool("sample") { tl!("Hide Sample") } else { tl!("Show Sample") }; + if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, label, 96.0)).inner.clicked() { + act = Some(Action::Sample); + } }); if let Some(k) = picked { select(d, k); @@ -192,6 +210,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { f.name = d.str("name"); ui.add_space(8.0); parts_table(app, ui, f); + if d.bool("sample") { + ui.add_space(8.0); + sample::show(ui, d, f); + } if d.bool("custom") { ui.add_space(8.0); ui.separator(); @@ -319,6 +341,10 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), Stri let open = !d.bool("custom"); d.fields.insert("custom".into(), json!(open)); } + Action::Sample => { + let open = !d.bool("sample"); + d.fields.insert("sample".into(), json!(open)); + } Action::NewSet | Action::DeleteSet | Action::AddChars | Action::DeleteChar => { let f = list.get_mut(i).ok_or("no composite font")?; let at = edit_sets(d, f, act)?; @@ -389,7 +415,7 @@ fn edit_sets(d: &mut Dialog, f: &mut CompositeFont, act: Action) -> Result Ok(None), + Action::New | Action::Delete | Action::Import | Action::Export | Action::Custom | Action::Sample => Ok(None), } } diff --git a/crates/ui-egui/src/dialogs/composite_fonts/sample.rs b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs new file mode 100644 index 0000000000..849eb63b51 --- /dev/null +++ b/crates/ui-egui/src/dialogs/composite_fonts/sample.rs @@ -0,0 +1,384 @@ +//! Show Sample in Composite Fonts: the font picked set in a line of sample text, with lines that +//! mark its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest +//! ascender and x-height, each shown or hidden by its button, at the size Zoom picks. +//! +//! The sample text, the zoom steps, the size at 100% and what each line measures are VectorCraft's +//! own: the em box and ICF box are those of the face of the part that sets the sample's first Kanji +//! (the Kanji part, or a custom set that holds that character) +//! ([`vectorcraft_text::FontFace::ideographic_centre`], [`vectorcraft_text::FontFace::icf_margins`]), +//! the cap height and x-height those of the face the Roman letters are drawn in, Max Ascent/Descent +//! the highest ascent and lowest descent among the faces the sample is drawn in (fallback faces +//! included), and Max Ascender the top of the sample's tallest glyph. Each takes its part's size, +//! baseline and vertical scale. +//! +//! Behavior reference (public documentation): +//! , +//! . + +use std::hash::{DefaultHasher, Hash, Hasher}; + +use egui::{Color32, Rect, Sense, Stroke, Ui, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{CharClass, CharStyle, CompositeClass, CompositeFont, FontHeightReference, TextObject}; +use vectorcraft_geom::kurbo::BezPath; +use vectorcraft_geom::{Affine, Point}; +use vectorcraft_text::FontDb; + +use crate::state::Dialog; +use crate::widgets; + +/// The text the sample sets: two Kanji, two kana, two punctuation marks, a symbol, Roman letters +/// with an ascender and a descender, and two numerals, then the first character of each custom set. +pub(super) const TEXT: &str = "永国あア、。※Agh12"; + +/// The Zoom menu's magnifications, in percent. +pub(super) const ZOOMS: [u64; 7] = [25, 50, 75, 100, 200, 400, 800]; + +/// The size the sample is set at with Zoom at 100%, in points. +const SIZE: f64 = 36.0; + +/// How tall the sample is drawn, in points. +const HEIGHT: f32 = 150.0; + +/// How far the sample text starts from the left edge, in points. +const INSET: f64 = 12.0; + +/// The width of the column of line buttons and Zoom beside the sample, in points. +const BUTTONS: f32 = 190.0; + +/// The narrowest and widest the sample is drawn, in points. +const WIDTH: std::ops::RangeInclusive = 240.0..=720.0; + +/// The name the sample lends the font under, so a name that is empty, being typed or shared with +/// another font still draws. +const NAME: &str = "VectorCraft Composite Sample"; + +/// A line Show Sample can mark. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Mark { + IcfBox, + EmBox, + Baseline, + CapHeight, + AscentDescent, + Ascender, + XHeight, +} + +impl Mark { + /// The marks, in the order their buttons show. + pub(super) const ALL: [Self; 7] = + [Self::IcfBox, Self::EmBox, Self::Baseline, Self::CapHeight, Self::AscentDescent, Self::Ascender, Self::XHeight]; + + /// The dialog field that holds whether the mark shows. + pub(super) fn field(self) -> &'static str { + match self { + Self::IcfBox => "lineIcfBox", + Self::EmBox => "lineEmBox", + Self::Baseline => "lineBaseline", + Self::CapHeight => "lineCapHeight", + Self::AscentDescent => "lineAscentDescent", + Self::Ascender => "lineAscender", + Self::XHeight => "lineXHeight", + } + } + + fn label(self) -> &'static str { + match self { + Self::IcfBox => tl!("ICF Box"), + Self::EmBox => tl!("Em Box"), + Self::Baseline => tl!("Baseline"), + Self::CapHeight => tl!("Cap Height"), + Self::AscentDescent => tl!("Max Ascent/Descent"), + Self::Ascender => tl!("Max Ascender"), + Self::XHeight => tl!("x-height"), + } + } + + /// Shown when the dialog opens: the em box, the ICF box and the baseline. + pub(super) fn shown_at_first(self) -> bool { + matches!(self, Self::IcfBox | Self::EmBox | Self::Baseline) + } + + fn color(self) -> Color32 { + match self { + Self::IcfBox => Color32::from_rgb(0, 150, 170), + Self::EmBox => Color32::from_rgb(220, 60, 60), + Self::Baseline => Color32::from_rgb(40, 110, 230), + Self::CapHeight => Color32::from_rgb(40, 160, 70), + Self::AscentDescent => Color32::from_rgb(230, 140, 30), + Self::Ascender => Color32::from_rgb(150, 80, 200), + Self::XHeight => Color32::from_rgb(200, 60, 160), + } + } +} + +/// The fields Show Sample adds to the dialog when it opens: hidden, at 100%, with the marks of +/// [`Mark::shown_at_first`]. +pub(super) fn defaults(fields: &mut serde_json::Map) { + fields.insert("sample".into(), json!(false)); + fields.insert("zoom".into(), json!(100)); + for m in Mark::ALL { + fields.insert(m.field().into(), json!(m.shown_at_first())); + } +} + +/// Why `ui.dialog.set` can't set Show Sample's `field` to the value `d` now holds: `sample` and the +/// marks take true or false, and `zoom` one of [`ZOOMS`]. +pub(super) fn check_field(d: &Dialog, field: &str) -> Result<(), String> { + let v = d.fields.get(field); + let key = field; + if field == "sample" || Mark::ALL.iter().any(|m| m.field() == field) { + if !v.is_some_and(Value::is_boolean) { + return Err(format!("`{key}` must be true or false")); + } + } else if field == "zoom" && !v.and_then(Value::as_u64).is_some_and(|z| ZOOMS.contains(&z)) { + return Err(format!("`{key}` must be one of {}", ZOOMS.map(|z| z.to_string()).join(", "))); + } + Ok(()) +} + +/// The Zoom `d` holds, 100 when it holds none of [`ZOOMS`]. +fn zoom(d: &Dialog) -> u64 { + d.fields.get("zoom").and_then(Value::as_u64).filter(|z| ZOOMS.contains(z)).unwrap_or(100) +} + +/// The heights the marks are drawn at, in points above the baseline (a mark's line is not drawn +/// when its height is `None`). The baseline is at 0. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Heights { + /// The em box's bottom and top. + pub em_box: Option<(f64, f64)>, + /// The ICF box's bottom and top. + pub icf_box: Option<(f64, f64)>, + pub cap_height: Option, + pub x_height: Option, + /// The lowest descent and the highest ascent. + pub ascent_descent: Option<(f64, f64)>, + /// The top of the tallest glyph. + pub ascender: Option, +} + +impl Heights { + /// The heights of mark `m`. + fn of(&self, m: Mark) -> Vec { + let pair = |p: Option<(f64, f64)>| p.map_or_else(Vec::new, |(a, b)| vec![a, b]); + match m { + Mark::IcfBox => pair(self.icf_box), + Mark::EmBox => pair(self.em_box), + Mark::Baseline => vec![0.0], + Mark::CapHeight => self.cap_height.into_iter().collect(), + Mark::AscentDescent => pair(self.ascent_descent), + Mark::Ascender => self.ascender.into_iter().collect(), + Mark::XHeight => self.x_height.into_iter().collect(), + } + } +} + +/// `f` as the sample sets it: named [`NAME`], without its custom sets when one of them can't be +/// used (a set whose name is empty or shared while it is typed). +fn sample_font(f: &CompositeFont) -> CompositeFont { + let mut s = f.clone(); + s.name = NAME.to_string(); + if s.check().is_err() { + s.custom.clear(); + } + s +} + +/// [`TEXT`], then the first character of each of `f`'s custom sets that it does not hold yet. +pub(super) fn text(f: &CompositeFont) -> String { + let mut t = TEXT.to_string(); + for c in f.custom.iter().filter_map(|s| s.characters.chars().next()) { + if !t.contains(c) { + t.push(c); + } + } + t +} + +/// The outlines of the sample of `f` set at `size` points with its baseline at y 0 (y down), and +/// the heights of its marks. +pub(super) fn measure(f: &CompositeFont, size: f64) -> (BezPath, Heights) { + let db = FontDb::global(); + let font = sample_font(f); + let _lent = db.lend_composite_fonts(std::slice::from_ref(&font)); + let text = text(&font); + let style = CharStyle { font_family: NAME.to_string(), size, ..Default::default() }; + let layout = vectorcraft_text::layout(db, &TextObject::point(Point::ZERO, &text, style)); + let path = layout.to_bezpath(); + let classes = font.classes(); + // The face of character `c`'s part, the face layout draws it in (a fallback face when the part's + // font lacks it), the size of its em and the shift of its baseline (points), and its part's + // vertical scale, as layout sets them: Kana scaled at center keep the middle of their part's em + // box where it is. + let placed = |c: char| { + let (part_face, _) = db.composite_resolve(NAME, c)?; + let drawn = text.find(c).and_then(|at| layout.glyphs.iter().find(|g| g.byte == at)).and_then(|g| db.face_by_id(g.font_id)); + let class = classes.of(c); + let p = font.part(class).unwrap_or(&font.parts.kanji); + let em = size * p.size / 100.0; + let mut shift = size * p.baseline / 100.0; + if class == CompositeClass::Fixed(CharClass::Kana) && p.scale_at_center && p.v_scale != 100.0 { + shift += em * part_face.ideographic_centre() * (1.0 - p.v_scale / 100.0); + } + let drawn = drawn.unwrap_or_else(|| part_face.clone()); + Some((part_face, drawn, em, shift, p.v_scale / 100.0)) + }; + let mut h = Heights::default(); + // The em box and ICF box are those of the part that sets the sample's first Kanji (the Kanji + // part, or a custom set that holds that character), as layout measures that part's face for + // Scale at Center. + if let Some((face, _, em, shift, v)) = TEXT.chars().next().and_then(placed) { + let tall = em * v; + let mid = shift + face.ideographic_centre() * tall; + let (bottom, top) = (mid - tall * 0.5, mid + tall * 0.5); + let m = face.icf_margins(); + h.em_box = Some((bottom, top)); + h.icf_box = Some((bottom + m.bottom * tall, top - m.top * tall)); + } + if let Some((_, face, em, shift, v)) = placed('A') { + let height = |r| face.font_height(r, false); + let cap = height(FontHeightReference::CapHeight).unwrap_or_else(|| face.cap_height() / face.units_per_em()); + h.cap_height = Some(shift + cap * em * v); + let x = height(FontHeightReference::XHeight).unwrap_or_else(|| face.x_height() / face.units_per_em()); + h.x_height = Some(shift + x * em * v); + } + let mut seen = Vec::new(); + for c in text.chars().filter(|c| !c.is_whitespace()) { + let Some((_, face, em, shift, v)) = placed(c) else { continue }; + if seen.contains(&(face.id(), em.to_bits(), shift.to_bits(), v.to_bits())) { + continue; + } + seen.push((face.id(), em.to_bits(), shift.to_bits(), v.to_bits())); + let (ascent, descent) = face.vertical_metrics(); + let scale = em * v / face.units_per_em(); + let (low, high) = (shift - descent * scale, shift + ascent * scale); + h.ascent_descent = Some(h.ascent_descent.map_or((low, high), |(l, t)| (l.min(low), t.max(high)))); + } + // Outlines, color glyphs and bitmap glyphs alike. + h.ascender = layout.ink_bounds().filter(|ink| ink.height() > 0.0).map(|ink| -ink.y0); + (path, h) +} + +/// The sample drawn for a key, kept until the font, zoom, size, display scale, text color or the +/// fonts installed change. +struct Drawn { + key: u64, + texture: Option, + heights: Heights, +} + +thread_local! { + static DRAWN: crate::graphics::TexCache> = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// Show Sample's area under the table: the sample of `f` with its marks, then the mark buttons and +/// Zoom beside it. +pub(super) fn show(ui: &mut Ui, d: &mut Dialog, f: &CompositeFont) { + let zoom = zoom(d); + ui.horizontal(|ui| { + let width = (ui.available_width() - BUTTONS).clamp(*WIDTH.start(), *WIDTH.end()); + let (rect, _) = ui.allocate_exact_size(vec2(width, HEIGHT), Sense::hover()); + paint(ui, rect, d, f, zoom); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for m in Mark::ALL { + let on = d.bool(m.field()); + ui.horizontal(|ui| { + let (swatch, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover()); + ui.painter().rect_filled(swatch, 1.0, m.color()); + if ui.add(egui::Button::selectable(on, m.label())).clicked() { + d.fields.insert(m.field().into(), json!(!on)); + } + }); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Zoom")); + let names: Vec = ZOOMS.iter().map(|z| format!("{z}%")).collect(); + let options: Vec<&str> = names.iter().map(String::as_str).collect(); + let current = format!("{zoom}%"); + if let Some(k) = widgets::dropdown(ui, "composite-fonts-zoom", ¤t, &options, 80.0) + && let Some(z) = ZOOMS.get(k) + { + d.fields.insert("zoom".into(), json!(z)); + } + }); + }); + }); +} + +/// Draw the sample of `f` at `zoom` percent into `rect`, its em box centered in it, with the marks +/// `d` shows. +fn paint(ui: &Ui, rect: Rect, d: &Dialog, f: &CompositeFont, zoom: u64) { + let painter = ui.painter_at(rect); + let visuals = ui.visuals(); + painter.rect_filled(rect, 2.0, visuals.extreme_bg_color); + let ppp = ui.ctx().pixels_per_point(); + let ink = visuals.text_color(); + let mut h = DefaultHasher::new(); + serde_json::to_string(f).unwrap_or_default().hash(&mut h); + (zoom, ppp.to_bits(), rect.width().to_bits(), rect.height().to_bits(), ink.to_array(), FontDb::global().generation()).hash(&mut h); + let key = h.finish(); + let size = SIZE * zoom as f64 / 100.0; + let (texture, heights) = DRAWN.with(|cache| { + let mut cache = cache.borrow_mut(); + if let Some(drawn) = cache.as_ref().filter(|c| c.key == key) { + return (drawn.texture.clone(), drawn.heights); + } + let (_, heights) = measure(f, size); + let texture = render(ui.ctx(), f, size, baseline(&heights, size, rect), rect, ppp, ink); + *cache = Some(Drawn { key, texture: texture.clone(), heights }); + (texture, heights) + }); + if let Some(t) = &texture { + painter.image(t.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + } + let base = rect.top() + baseline(&heights, size, rect) as f32; + for m in Mark::ALL.into_iter().filter(|m| d.bool(m.field())) { + for y in heights.of(m) { + painter.hline(rect.x_range(), base - y as f32, Stroke::new(1.0, m.color())); + } + } + painter.rect_stroke(rect, 2.0, visuals.widgets.noninteractive.bg_stroke, egui::StrokeKind::Inside); +} + +/// Where the baseline goes, in points down from the top of `rect`: the em box's middle (else +/// 0.38 em above the baseline) at the middle of `rect`. +fn baseline(h: &Heights, size: f64, rect: Rect) -> f64 { + let mid = h.em_box.map_or(size * 0.38, |(bottom, top)| (bottom + top) * 0.5); + f64::from(rect.height()) * 0.5 + mid +} + +/// The sample of `f` drawn into a texture the size of `rect` in pixels ([`draw`]). `None` when +/// `rect` is empty or larger than the largest texture. +fn render(ctx: &egui::Context, f: &CompositeFont, size: f64, baseline: f64, rect: Rect, ppp: f32, ink: Color32) -> Option { + let (w, h) = ((rect.width() * ppp).round(), (rect.height() * ppp).round()); + let max = ctx.input(|i| i.max_texture_side) as f32; + if w < 1.0 || h < 1.0 || w > max || h > max || w > f32::from(u16::MAX) || h > f32::from(u16::MAX) { + return None; + } + let image = draw(f, size, baseline, (w as u16, h as u16), ppp, ink); + Some(ctx.load_texture("composite-font-sample", crate::canvas::color_image_owned(image), egui::TextureOptions::LINEAR)) +} + +/// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the +/// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own +/// colors) into `px` pixels at `ppp` pixels per point. +pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered { + let (w, h) = px; + let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp)); + let font = sample_font(f); + let sample = text(&font); + *doc.composite_fonts = vec![font]; + let [r, g, b, _] = ink.to_normalized_gamma_f32(); + let fill = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(r, g, b)); + let style = CharStyle { font_family: NAME.to_string(), size, fill, ..Default::default() }; + let t = TextObject::point(Point::new(INSET, baseline), &sample, style); + let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t)))); + let view = Affine::scale(f64::from(ppp)); + let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] }; + RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty) +} diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index e50ce1b566..fa909973b1 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -280,3 +280,193 @@ fn custom_sets_sharing_a_name_keep_the_dialog_open() { assert!(app.ui.dialog.is_some()); assert!(names(&app).is_empty()); } + +/// A composite font set in Inter, with its Roman part as `roman` changes it. +fn inter_font(roman: impl FnOnce(&mut vectorcraft_doc::CompositePart)) -> CompositeFont { + let mut parts = vectorcraft_doc::CompositeParts::all(vectorcraft_doc::CompositePart::new("Inter", "Regular")); + roman(&mut parts.roman); + CompositeFont { name: "UI Composite Sample".into(), parts, custom: Vec::new() } +} + +/// Show Sample opens hidden at 100% with the ICF box, em box and baseline shown; its button shows +/// and hides the sample, which draws with every line shown and at every zoom; nothing changes in +/// the document. +#[test] +fn show_sample_shows_and_hides_the_sample() { + let mut app = app(); + open(&mut app).unwrap(); + let d = dialog(&mut app); + assert!(!d.bool("sample")); + assert_eq!(d.fields.get("zoom"), Some(&json!(100))); + let shown: Vec = sample::Mark::ALL.iter().map(|m| d.bool(m.field())).collect(); + assert_eq!(shown, [true, true, true, false, false, false, false]); + press(&mut app, Action::New); + press(&mut app, Action::Sample); + assert!(dialog(&mut app).bool("sample")); + frame(&mut app); + for m in sample::Mark::ALL { + dialog(&mut app).fields.insert(m.field().into(), json!(true)); + } + for z in sample::ZOOMS { + dialog(&mut app).fields.insert("zoom".into(), json!(z)); + frame(&mut app); + } + press(&mut app, Action::Sample); + assert!(!dialog(&mut app).bool("sample")); + super::super::cancel(&mut app); + assert!(names(&app).is_empty()); +} + +/// `ui.dialog.set` takes `sample`, `zoom` and the line fields; a zoom outside the Zoom menu or a +/// line that is not true or false is refused and leaves the dialog as it was. +#[test] +fn sample_fields_are_set_and_checked() { + let mut app = app(); + let ctx = egui::Context::default(); + open(&mut app).unwrap(); + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("not done") }; + r + }; + for (field, value) in [("sample", json!(true)), ("zoom", json!(400)), ("lineCapHeight", json!(true)), ("lineBaseline", json!(false))] { + let r = set(&mut app, field, value.clone()); + assert!(r.get("error").is_none(), "{field}: {r}"); + assert_eq!(dialog(&mut app).fields.get(field), Some(&value), "{field}"); + } + for (field, value) in [("zoom", json!(30)), ("zoom", json!("200")), ("sample", json!(1)), ("lineXHeight", json!("yes"))] { + let r = set(&mut app, field, value.clone()); + assert!(r.get("error").is_some(), "{field} {value}: {r}"); + } + let d = dialog(&mut app); + assert_eq!((d.fields.get("zoom"), d.bool("sample"), d.bool("lineXHeight")), (Some(&json!(400)), true, false)); +} + +/// The sample's lines: the em box and ICF box of the face the Kanji are set in (a face without +/// ideographs centers its em box 0.38 em above the baseline), the cap height and x-height of the +/// Roman part's face raised by its baseline and scaled by its vertical scale, the lowest descent +/// and highest ascent, and the top of the tallest glyph; all of them grow with the size. +#[test] +fn sample_lines_follow_the_parts() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let (path, h) = sample::measure(&inter_font(|_| {}), 36.0); + assert!(!path.elements().is_empty()); + let (bottom, top) = h.em_box.unwrap(); + assert!(close(bottom, -0.12 * 36.0) && close(top, 0.88 * 36.0), "{h:?}"); + let (ib, it) = h.icf_box.unwrap(); + assert!(ib >= bottom && it <= top && ib < it, "{h:?}"); + let (cap, x) = (h.cap_height.unwrap(), h.x_height.unwrap()); + assert!(0.0 < x && x < cap && cap < top, "{h:?}"); + let (low, high) = h.ascent_descent.unwrap(); + assert!(low < 0.0 && high > cap, "{h:?}"); + assert!(h.ascender.unwrap() > x, "{h:?}"); + // The Roman part raised by 10% and squeezed to half height moves its lines; the Kanji's stay. + let (_, raised) = sample::measure( + &inter_font(|p| { + p.baseline = 10.0; + p.v_scale = 50.0; + }), + 36.0, + ); + assert!(close(raised.cap_height.unwrap(), 3.6 + cap * 0.5), "{raised:?}"); + assert!(close(raised.x_height.unwrap(), 3.6 + x * 0.5), "{raised:?}"); + assert_eq!(raised.em_box, h.em_box); + // At 200% every line is twice as far from the baseline. + let (_, double) = sample::measure(&inter_font(|_| {}), 72.0); + assert!(close(double.cap_height.unwrap(), cap * 2.0) && close(double.em_box.unwrap().1, top * 2.0), "{double:?}"); +} + +/// The ICF box is the Kanji face's ideographic character face inside its em box, and a Roman face +/// without an OS/2 cap height still gets a Cap Height line, estimated from its ascent. +#[test] +fn sample_lines_read_the_icf_box_and_estimate_a_missing_cap_height() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, HEIGHTLESS_FAMILY, height_font}; + let db = vectorcraft_text::FontDb::global(); + db.add_font(height_font(true).expect("the test font builds")); + db.add_font(height_font(false).expect("the test font builds")); + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let mut f = inter_font(|p| p.font = HEIGHTLESS_FAMILY.into()); + f.parts.kanji.font = HEIGHT_FAMILY.into(); + let (_, h) = sample::measure(&f, 36.0); + let (bottom, top) = h.icf_box.unwrap(); + assert!(close(bottom, -0.07 * 36.0) && close(top, 0.83 * 36.0), "{h:?}"); + let cap = h.cap_height.expect("an estimated cap height"); + assert!(cap > h.x_height.unwrap() && cap < h.ascent_descent.unwrap().1, "{h:?}"); +} + +/// A character its part's font lacks is drawn in a fallback face, and the lines measure that face: +/// in a font whose box runs to 0.9 em and which maps no `A`, `g`, `h`, `1` or `2`, the highest +/// ascent is the fallback face's. +#[test] +fn sample_lines_measure_the_faces_that_draw_the_glyphs() { + use vectorcraft_text::test_fonts::{PATH_ALIGN_HHEA_FAMILY, path_align_font}; + vectorcraft_text::FontDb::global().add_font(path_align_font(PATH_ALIGN_HHEA_FAMILY).expect("the test font builds")); + let mut f = inter_font(|_| {}); + f.parts = vectorcraft_doc::CompositeParts::all(vectorcraft_doc::CompositePart::new(PATH_ALIGN_HHEA_FAMILY, "Regular")); + let (_, h) = sample::measure(&f, 36.0); + let (_, high) = h.ascent_descent.unwrap(); + assert!(high > 0.9 * 36.0 + 0.5, "{h:?}"); +} + +/// The lines follow a vertical scale as the glyphs do: a custom set that holds the first Kanji at +/// half height halves the em box about its baseline, and Kana scaled at center keep the middle of +/// their em box, so their ascent moves up by the half they lose below it. +#[test] +fn sample_lines_follow_vertical_scale() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let mut f = inter_font(|_| {}); + let mut half = vectorcraft_doc::CompositePart::new("Inter", "Regular"); + half.v_scale = 50.0; + f.custom = vec![CustomCharSet { name: "Half".into(), characters: "永".into(), part: half }]; + let (_, h) = sample::measure(&f, 36.0); + let (bottom, top) = h.em_box.unwrap(); + assert!(close(bottom, (0.38 - 0.5) * 18.0) && close(top, (0.38 + 0.5) * 18.0), "{h:?}"); + let kana = |at_center: bool| { + let mut f = inter_font(|_| {}); + f.parts.kana.size = 300.0; + f.parts.kana.v_scale = 50.0; + f.parts.kana.scale_at_center = at_center; + sample::measure(&f, 36.0).1.ascent_descent.unwrap() + }; + // The Kana, at three times the size, give the highest ascent either way. + let ((_, high), (_, raised)) = (kana(false), kana(true)); + assert!(close(raised, high + 0.38 * 108.0 * 0.5), "{high} {raised}"); +} + +/// The sample adds the first character of each custom set it does not hold yet, and a font whose +/// sets can't be used yet (two sharing a name while it is typed) still draws, without them. +#[test] +fn the_sample_takes_the_custom_sets() { + let mut f = inter_font(|_| {}); + let set = |name: &str, characters: &str| CustomCharSet { + name: name.into(), + characters: characters.into(), + part: vectorcraft_doc::CompositePart::new("Inter", "Regular"), + }; + f.custom = vec![set("Marks", "〒※"), set("Letters", "A")]; + assert_eq!(sample::text(&f), format!("{}〒", sample::TEXT)); + f.custom = vec![set("Marks", "〒"), set("marks", "〒")]; + let (path, h) = sample::measure(&f, 36.0); + assert!(!path.elements().is_empty() && h.cap_height.is_some()); +} + +/// The sample draws a color font's glyphs in their own colors, not in the dialog's text color. +#[test] +fn the_sample_draws_color_glyphs_in_their_colors() { + use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font}; + vectorcraft_text::FontDb::global().add_font(colr_font(false).expect("the test font builds")); + let mut f = inter_font(|_| {}); + let mut colr = vectorcraft_doc::CompositePart::new(colr_family(false), "Regular"); + colr.size = 300.0; + f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }]; + let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK); + let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| { + let p = img.pixel(x, y); + p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200 + }); + assert!(red, "the glyph's red layer is drawn"); + // Max Ascender reaches the top of the color glyph, three times the size of the rest. + let (_, plain) = sample::measure(&inter_font(|_| {}), 36.0); + let (_, tall) = sample::measure(&f, 36.0); + assert!(tall.ascender.unwrap() > plain.ascender.unwrap() * 1.5, "{plain:?} {tall:?}"); +} diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 033e194e50..d386c1f028 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -995,7 +995,7 @@ pub(crate) fn preview(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mu /// As [`preview`], returning the command's result only when a new preview succeeds. /// A dialog can retain a small summary (such as point counts) in its private fields. -pub(super) fn preview_result( +pub(crate) fn preview_result( app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 98d6225c17..ec99667fbb 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -344,5 +344,9 @@ pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, ids: &[&str], fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let (format, path) = (d.str("format"), d.str("path")); app.ui.dialog = None; - io::export(app, Some(&format), Some(path), &super::export_as::exported(d, form::params(d))) + let mut params = form::params(d); + if format == "psd" { + psd_options::drop_unused(&mut params); + } + io::export(app, Some(&format), Some(path), &super::export_as::exported(d, params)) } diff --git a/crates/ui-egui/src/dialogs/psd_options.rs b/crates/ui-egui/src/dialogs/psd_options.rs index df31d80bb0..68aad6bf58 100644 --- a/crates/ui-egui/src/dialogs/psd_options.rs +++ b/crates/ui-egui/src/dialogs/psd_options.rs @@ -1,5 +1,5 @@ -//! The options of PSD (colour model, a flat image or layers, Maximum Editability, hidden layers, -//! profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the +//! The options of PSD (colour model, a flat image or layers, Preserve Text Editability, Maximum +//! Editability, hidden layers, profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the //! `psdOptions` dialog. use serde_json::{Map, Value, json}; @@ -17,12 +17,23 @@ pub(super) fn defaults(cmyk: bool, o: &mut Map) { o.extend([ ("colorModel".into(), json!(model.id())), ("layers".into(), json!(p.layers)), + ("preserveText".into(), json!(p.preserve_text)), ("maxEditability".into(), json!(p.max_editability)), ("hiddenLayers".into(), json!(p.hidden_layers)), ("embedIcc".into(), json!(p.embed_icc)), ]); } +/// Flat Image writes no layers: the options that need them are left out of the export's params +/// (`preserveText`, which the export refuses without layers). +pub(super) fn drop_unused(p: &mut Value) { + if p["layers"] == json!(false) + && let Some(o) = p.as_object_mut() + { + o.remove("preserveText"); + } +} + /// The grid rows of PSD's own options. pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { label(ui, tl!("Color Model:")); @@ -36,7 +47,11 @@ pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui:: d.fields.insert("layers".into(), json!(layers)); } ui.add_enabled_ui(layers, |ui| { - for (key, text) in [("maxEditability", tl!("Maximum Editability")), ("hiddenLayers", tl!("Include Hidden Layers"))] { + for (key, text) in [ + ("preserveText", tl!("Preserve Text Editability")), + ("maxEditability", tl!("Maximum Editability")), + ("hiddenLayers", tl!("Include Hidden Layers")), + ] { ui.horizontal(|ui| { ui.add_space(22.0); form::check(ui, d, key, text); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 238205216e..aacb84da72 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -9,7 +9,8 @@ //! CMYK or Lab, and Tint when the new color is a spot color of the library), which edit the //! first selected row's new color (once they have, OK gives the art each new color in its own //! model), New Row (a row with no current colors above the first selected row, or at the top, -//! with that row's new color; it recolors nothing until Merge moves colors into it), Merge and +//! with that row's new color; it recolors nothing until Merge moves colors into it, and until then +//! the Edit tab, the Color Theme Picker and Save All Colors leave it out), Merge and //! Separate, Randomize order or //! saturation and brightness, Find (with it on, the art of the selected rows shows as the preview //! shows it, their current colors with Preview off, and the rest of the selected art shows its @@ -38,9 +39,9 @@ //! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an //! object takes the palette of the object a Selection tool click takes, a drag takes the palette //! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The -//! rows that aren't excluded take the picked colors as their new colors, the most used color first -//! and repeating when the rows outnumber them, and the art previews them; OK keeps them as one -//! undo step. A new count of Colors keeps the picks: the new rows take them again. +//! rows that aren't excluded and hold current colors take the picked colors as their new colors, +//! the most used color first and repeating when the rows outnumber them, and the art previews +//! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again. //! //! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot //! color}]), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`, @@ -391,14 +392,15 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), - _ => (0..rs.len()).filter(|&i| !excluded(&rs[i])).collect(), + _ => (0..rs.len()).filter(|&i| in_group(&rs[i])).collect(), }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { @@ -417,10 +419,10 @@ const THEME_PICKER: &str = "themePicker"; const THEME_PICKS: &str = "themePicks"; const THEME_DONE: &str = "__themePicked"; -/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded the -/// palette of the art picked (`recolor.pickTheme`, as many colors as those rows), in row order; -/// with fewer colors than rows, the colors repeat. Picks that touch no art leave the rows as they -/// are. +/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded and hold +/// current colors the palette of the art picked (`recolor.pickTheme`, as many colors as those +/// rows), in row order; with fewer colors than rows, the colors repeat. Picks that touch no art +/// leave the rows as they are. fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) { let picks = d.fields.get(THEME_PICKS).cloned().unwrap_or(Value::Null); if !picks.as_array().is_some_and(|a| !a.is_empty()) || d.fields.get(THEME_DONE) == Some(&picks) { @@ -559,6 +561,18 @@ fn excluded(row: &Value) -> bool { row["exclude"].as_bool().unwrap_or(false) } +/// Whether `row` holds no current colors: a row made with New Row, until colors are merged into it. +/// Its new color recolors nothing and is no color of a color group, the wheel or the harmony rules. +fn empty(row: &Value) -> bool { + row["from"].as_array().is_some_and(Vec::is_empty) +} + +/// Whether `row`'s new color is one of the colors a color group takes: the row isn't excluded and +/// holds current colors. +fn in_group(row: &Value) -> bool { + !excluded(row) && !empty(row) +} + /// The seed for the next Randomize: one past the last, held at `u64::MAX`. fn next_seed(d: &Dialog) -> u64 { (d.f64("__seed", 0.0) as u64).saturating_add(1) @@ -574,7 +588,7 @@ fn apply_params(d: &Dialog) -> Value { let rs = rows(d); let group = d.fields.get("group").and_then(Value::as_str).map(|g| { // A row made with New Row that holds no current colors gives the group no color. - let filled: Vec<&Value> = rs.iter().filter(|r| !r["from"].as_array().is_some_and(Vec::is_empty)).map(|r| &r["to"]).collect(); + let filled: Vec<&Value> = rs.iter().filter(|r| !empty(r)).map(|r| &r["to"]).collect(); let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")); let rest = assign.map_or(&[][..], |a| a.get(filled.len()..).unwrap_or_default()); let colors: Vec<&Value> = filled.into_iter().chain(rest).collect(); @@ -787,7 +801,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { sync_theme(app, &mut d); sync_weights(app, &mut d); if d.bool("__newGroup") { - let colors = group_colors(app, &d, rows(&d).iter().filter(|r| !excluded(r))); + let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); } let r = form::commit_preview(app, CMD, apply_params(&d))?; @@ -1000,7 +1014,8 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target, false)); }); ui.add_space(6.0); - changed |= sliders(app, ui, d, rows); + let row = first_selected(d, rows); + changed |= sliders(app, ui, d, rows, row); ui.add_space(8.0); egui::Grid::new("recolor-options").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { ui.label(egui::RichText::new(tl!("Method:")).color(t.text_dim)); @@ -1131,8 +1146,13 @@ fn slider_values(d: &Dialog, rows: &[Value], i: usize, c: &Color, mode: Mode) -> v.filter(|v| v.len() == mode.labels().len()).unwrap_or_else(|| components(mode, c)) } -/// What the color sliders edit: the first selected row, its new color, and the name of the -/// library's spot color that color is. +/// The first selected row of `rows`. +fn first_selected(d: &Dialog, rows: &[Value]) -> Option { + selection(d).into_iter().filter(|i| *i < rows.len()).min() +} + +/// What the color sliders edit: a row (the first selected row on the Assign tab, the base color's +/// row on the Edit tab), its new color, and the name of the library's spot color that color is. struct SliderTarget { row: Option, color: Option, @@ -1141,7 +1161,12 @@ struct SliderTarget { impl SliderTarget { fn of(app: &VectorcraftApp, d: &Dialog, rows: &[Value]) -> Self { - let row = selection(d).into_iter().filter(|i| *i < rows.len()).min(); + Self::at(app, d, rows, first_selected(d, rows)) + } + + /// What the color sliders edit when they edit row `row`. + fn at(app: &VectorcraftApp, d: &Dialog, rows: &[Value], row: Option) -> Self { + let row = row.filter(|i| *i < rows.len()); let color = row.and_then(|i| to_color(&rows[i])); // A row tint acts only on art, so without art a spot color shows the process modes. let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c)); @@ -1252,11 +1277,11 @@ fn slider_cell( dragged.map(|x| (lo + f64::from(x) * (hi - lo)).round()).or(keyed).or(typed).map(|v| v.clamp(lo, hi)).filter(|v| (v - value).abs() > 1e-6) } -/// The color sliders under the rows, two to a line: they edit the first selected row's new color -/// (the others keep theirs) in the mode of [`mode_menu`], or its tint of a spot color of the -/// library. Without a selected row they are disabled. Returns true when they changed a row. -fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { - let target = SliderTarget::of(app, d, rows); +/// The color sliders, two to a line: they edit row `row`'s new color (the others keep theirs) in +/// the mode of [`mode_menu`], or its tint of a spot color of the library. Without a row they are +/// disabled. Returns true when they changed a row. +fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], row: Option) -> bool { + let target = SliderTarget::at(app, d, rows, row); let mode = target.mode(d); let mut changed = false; let top = ui.cursor().top(); @@ -1357,9 +1382,17 @@ fn new_row(rows: &mut Vec, sel: &[usize]) -> usize { at } -/// The rows the Edit tab shows: those with a new colour, not excluded. +/// The rows the Edit tab shows, the harmony rules fill and the Color Theme Picker recolors: those +/// with a new colour that aren't excluded and hold current colors. fn active_rows(rows: &[Value]) -> Vec { - (0..rows.len()).filter(|i| !excluded(&rows[*i]) && to_color(&rows[*i]).is_some()).collect() + (0..rows.len()).filter(|i| in_group(&rows[*i]) && to_color(&rows[*i]).is_some()).collect() +} + +/// The row the Edit tab's color sliders edit: the first selected row when the tab shows it (one of +/// `active`), else the base color's row `base`. A selected row the tab does not show (excluded, or +/// empty) is left as it is. +fn edit_slider_row(d: &Dialog, rows: &[Value], active: &[usize], base: Option) -> Option { + first_selected(d, rows).filter(|i| active.contains(i)).or(base) } /// Set row `i`'s new colour to hue/saturation/brightness `hsb` ([`move_on_wheel`]: with `linked` @@ -1388,7 +1421,8 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value let linked = d.bool("linked"); let active = active_rows(rows); let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied()); - let target = SliderTarget::of(app, d, rows); + let slider_row = edit_slider_row(d, rows, &active, base); + let target = SliderTarget::at(app, d, rows, slider_row); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim)); let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary); @@ -1411,7 +1445,7 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value let button = widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0); let prominent = d.bool("__art") && !prominent_parts(d, rows).is_empty(); let saved = egui::Popup::menu(&button).show(|ui| { - if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(|r| !excluded(r)), false) { + if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(in_group), false) { return Some("all"); } widgets::menu_item_name(ui, tl!("Save Prominent Colors"), prominent, false).then_some("prominent") @@ -1489,7 +1523,7 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25)); global_sliders(ui, d, sample); } else { - changed |= sliders(app, ui, d, rows); + changed |= sliders(app, ui, d, rows, slider_row); } // The new colours: click one to make it the base colour. let min_height = (TAB_H - (ui.cursor().top() - top)).max(0.0); @@ -1708,6 +1742,27 @@ mod tests { assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"])); } + /// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the + /// new color group, in row order: an empty row gives it no color. + #[test] + fn an_empty_row_gives_a_new_group_no_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": ["#ff8000", "#0080ff"]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + let at = new_row(&mut rs, &[1]); + rs[at]["to"] = json!("rgb 255 0 255"); + d.fields.insert("rows".into(), Value::Array(rs)); + let d = d.clone(); + let groups = app.session.doc().unwrap().doc.swatch_groups.len(); + confirm(&mut app, &d).unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), groups + 1, "a new color group"); + let colors: Vec = doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); + assert_eq!(colors, ["#ff8000", "#0080ff"]); + } + /// Randomize after a seed past `u64::MAX` keeps the largest seed. #[test] fn next_seed_holds_at_the_largest() { @@ -1740,6 +1795,27 @@ mod tests { assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"]], ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]); } + /// A row made with New Row is not on the Edit tab while it is empty: a harmony rule gives it + /// no color and a linked move leaves its new color as it is. + #[test] + fn an_empty_row_takes_no_harmony_or_wheel_color() { + let mut r = rows(); + new_row(&mut r, &[]); + assert_eq!(r[0]["to"], "rgb 255 0 0"); + let active = active_rows(&r); + assert_eq!(active, [1, 2, 3]); + apply_rule(&mut r, Harmony::Triad, 1, Color::rgb(1.0, 0.0, 0.0), &active); + assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"], &r[3]["to"]], ["rgb 255 0 0", "rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]); + move_color(&mut r, 1, [120.0, 1.0, 1.0], true); + assert_eq!(r[1]["to"], "rgb 0 255 0"); + assert_eq!(r[0]["to"], "rgb 255 0 0", "the empty row keeps its new color"); + // With the empty row selected, the sliders edit the base color's row instead. + let sel = |s: Value| Dialog::new("recolor", json!({"__sel": s})); + assert_eq!(edit_slider_row(&sel(json!([0])), &r, &active, Some(1)), Some(1)); + assert_eq!(edit_slider_row(&sel(json!([3, 2])), &r, &active, Some(3)), Some(2), "a shown row: the first selected"); + assert_eq!(edit_slider_row(&sel(json!([0])), &r, &[], None), None, "no row to edit"); + } + /// A rule or a wheel move that gives a row a new color drops the row's tint; a row whose /// color stays keeps it. #[test] @@ -1993,6 +2069,23 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "the art is unchanged: no undo step"); } + /// The Color Theme Picker gives its colors only to the rows that hold current colors: a row + /// made with New Row keeps its new color and takes no place in the palette. + #[test] + fn theme_picks_leave_an_empty_row_out() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + theme_setup(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + let at = new_row(&mut rs, &[]); + rs[at]["to"] = json!("rgb 9 9 9"); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert(THEME_PICKS.into(), json!([{"at": [107, 17]}, {"rect": [125, 5, 150, 30]}])); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 9 9 9"), json!("rgb 0 255 0"), json!("rgb 255 255 0")]); + } + /// A row made with New Row recolors nothing while it is empty, and OK keeps it; the blue art's /// color merged into it takes its new color, in the preview and at OK. #[test] @@ -2163,6 +2256,33 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "a step for each group"); } + /// Save All Colors leaves out a row made with New Row while it is empty; with only empty rows + /// it saves no group and records no step. + #[test] + fn save_all_colors_leaves_an_empty_row_out() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + prominent_setup(&mut app, &ctx); + let groups = |app: &VectorcraftApp| app.session.doc().unwrap().doc.swatch_groups.len(); + let (n, undo) = (groups(&app), app.session.doc().unwrap().history.undo.len()); + let save = |app: &mut VectorcraftApp, rows: Value, t: f64| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("rows".into(), rows); + d.fields.insert(SAVE_GROUP.into(), json!("all")); + frame(app, &ctx, t, vec![], 0); + frame(app, &ctx, t + 0.01, vec![], 0); + }; + let blank = json!({"from": [], "to": "rgb 255 0 255"}); + save(&mut app, json!([blank, {"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}]), 0.1); + let doc = &app.session.doc().unwrap().doc; + let colors: Vec = doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); + assert_eq!(colors, ["#ffff00", "#00ff00"]); + assert_eq!(groups(&app), n + 1); + save(&mut app, json!([blank, {"from": [BLUE, RED, PURPLE], "to": "rgb 0 255 0", "exclude": true}]), 0.2); + assert_eq!(groups(&app), n + 1, "only an empty and an excluded row: no group"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "and no step"); + } + /// One frame with `modifiers` held. fn frame_with(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec, modifiers: egui::Modifiers) { let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 672ee10ec2..77c5980ec0 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -120,7 +120,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) number(ui, d, "offset", tl!("Offset"), (0.0, 100000.0), "", 1, Some(unit)); ui.horizontal(|ui| { let cap = flag(d, "cap", true); - let tip = tl!("Close the circular ends of open profiles. Partial sweeps keep their cut sides open."); + let tip = tl!("Close the circular ends of open profiles. Partial sweeps also close their cut sides."); if widgets::check3_tip(ui, c3("Cap"), cap, true, tip) { d.fields.insert("cap".into(), json!(cap != Some(true))); } diff --git a/crates/ui-egui/src/dialogs/tests_psd.rs b/crates/ui-egui/src/dialogs/tests_psd.rs index a59cf58901..1816d56342 100644 --- a/crates/ui-egui/src/dialogs/tests_psd.rs +++ b/crates/ui-egui/src/dialogs/tests_psd.rs @@ -14,8 +14,8 @@ fn psd_options_pick_flat_or_layers_and_the_colour_model() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((spec(&d.kind).heading)(d), "PSD Options"); assert_eq!( - (d.str("colorModel"), d.bool("layers"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")), - ("rgb".into(), true, false, false, true) + (d.str("colorModel"), d.bool("layers"), d.bool("preserveText"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")), + ("rgb".into(), true, false, false, false, true) ); assert!(tiff_bmp_tga::keeps_alpha("psd", d), "layers keep transparency"); frame(&mut app); @@ -30,9 +30,11 @@ fn psd_options_pick_flat_or_layers_and_the_colour_model() { assert_eq!(i16::from_be_bytes([psd[at + 8], psd[at + 9]]), -3); assert!(app.ui.dialog.is_none()); - // Flat: flattened on white, so the background list starts at White. + // Flat: flattened on white, so the background list starts at White. Preserve Text + // Editability, still ticked, isn't sent: the export refuses it without layers. app.run("file.exportAs", json!({"format": "psd"})).unwrap(); confirm(&mut app).unwrap(); + set(&mut app, "preserveText", json!(true)); set(&mut app, "layers", json!(false)); set(&mut app, "colorModel", json!("gray")); assert!(!tiff_bmp_tga::keeps_alpha("psd", app.ui.dialog.as_ref().unwrap())); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index c5070d67f2..412eddac98 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -31,6 +31,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width: ui.set_max_height(tall); panels::libraries(app, ui); } + None if id == "color" && widgets::panel_footer_bottom(ui).is_some() => panels::color::show_sized(app, ui, tall), None => panels::show_icon_panel(app, ui, id), } }); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 9b829114c2..084311e93c 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -4,7 +4,10 @@ //! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in //! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text //! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the -//! document. A star marks a favourite family, and the ★ filter lists only those. The Font +//! document. A star marks a favourite family, and the ★ filter lists only those. The ≈ button +//! before a family's star (Show Similar Fonts) orders the listed families by how alike they look to +//! it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent +//! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable //! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays //! out its filters on the same four rows wherever it opens. However narrow its field, it opens at @@ -160,6 +163,8 @@ impl<'a> MenuLook<'a> { const ROW: f32 = 24.0; /// Width of the star at the end of a family's row. const STAR: f32 = 18.0; +/// Width of the Show Similar Fonts button before the star. +const SIMILAR: f32 = 18.0; /// The least share of a row the family's name takes when the row is too narrow for the widest /// name and [`SAMPLE_W`]; the sample fills the rest. const NAME_SHARE: f32 = 0.5; @@ -305,8 +310,8 @@ fn remap_highlight(before: &[Row], selected: Option, after: &[Row]) -> Op /// What the rows were listed for: the query, the script, kind, font technology (variable only) and /// favourites filters, Show Font Names in English, the expanded families, favourites, recent -/// history and font list generation. -type RowsKey = (String, usize, Option, bool, bool, bool, Vec, Vec, Vec, u64); +/// history, font list generation and the family Show Similar Fonts orders by. +type RowsKey = (String, usize, Option, bool, bool, bool, Vec, Vec, Vec, u64, Option); /// The menu's state between frames. #[derive(Clone, Default)] @@ -330,6 +335,12 @@ struct MenuState { favorites_only: bool, /// Families whose styles are listed (lowercase). expanded: Vec, + /// Show Similar Fonts: the family the list is ordered by likeness to, until it is cleared or + /// the menu closes. + similar: Option, + /// Show Similar Fonts was chosen or cleared: the family it ordered by, which is highlighted + /// and scrolled to once (to the top while the list is ordered by it). + similar_moved: Option, /// What was previewed last (None: nothing is previewed). previewed: Option<(String, Option)>, /// The rows listed, and what for: built again only when that changes, not every frame. @@ -1043,6 +1054,8 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, st.highlight = None; st.query.clear(); st.current = current.to_string(); + st.similar = None; + st.similar_moved = None; } st.last = pass; // For [`end_stale_preview`]: the menu is open, in this layer. @@ -1080,10 +1093,15 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, look.favorites.to_vec(), look.recent.to_vec(), db.generation(), + st.similar.clone(), ); if st.rows_key.as_ref() != Some(&key) { let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect(); - let rows = grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)); + // Show Similar Fonts orders every listed family by likeness, the recent ones among them. + let rows = match &st.similar { + Some(base) => grouped_rows(&db.similar_families(base, &families), &[], &st.expanded, |f| db.styles(f)), + None => grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)), + }; // Filter changes (including un-starring a favourite) may remove rows; expanding // another family or a background font scan can insert rows before the highlight. // Never preview an unrelated family because the old numeric index now points to it. @@ -1096,6 +1114,9 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, st.query = query.clone(); st.highlight = None; } + if let Some(base) = &st.similar_moved { + st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(base))); + } if st.highlight.is_none() && query.is_empty() { st.highlight = rows.iter().position(|r| matches!(r, Row::Family(f) if f.eq_ignore_ascii_case(current))); } @@ -1196,16 +1217,29 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool { }); } st.filters = widest; + // While Show Similar Fonts orders the list: the family it orders by, which clears it. Its + // width is left out of the widest row: a long name wraps instead of widening the menu. + if let Some(base) = st.similar.clone() { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 2.0); + let chip = egui::RichText::new(format!("≈ {base} ✕")).size(FILTER_SIZE); + if ui.selectable_label(true, chip).on_hover_text(tl!("Clear Similar Fonts")).clicked() { + st.similar_moved = st.similar.take(); + refilter = true; + } + }); + } refilter } /// The width the open menu takes at least: the widest row of filters last frame, and the widest -/// name up to [`NAME_MAX`] with room for its sample, the star and the scroll bar beside it, within -/// [`WINDOW_SHARE`] of the window. The menu is never narrower than its field. +/// name up to [`NAME_MAX`] with room for its sample, the Show Similar Fonts button, the star and the +/// scroll bar beside it, within [`WINDOW_SHARE`] of the window. The menu is never narrower than its +/// field. fn menu_width(ui: &Ui, st: &MenuState, look: MenuLook) -> f32 { let sample = if look.samples { SAMPLE_W } else { 0.0 }; let names = name_width(ui, vectorcraft_text::FontDb::global(), look.english_names, &st.rows).min(NAME_MAX); - let row = DISCLOSURE + names + NAME_GAP + sample + STAR + 2.0 + widgets::list_scroll_style().allocated_width(); + let row = DISCLOSURE + names + NAME_GAP + sample + SIMILAR + STAR + 2.0 + widgets::list_scroll_style().allocated_width(); // Rounding in the chips' widths must not wrap the widest row. let filters = if st.filters > 0.0 { st.filters.ceil() + 1.0 } else { 0.0 }; filters.max(row).min(ui.ctx().content_rect().width() * WINDOW_SHARE) @@ -1267,13 +1301,14 @@ fn widest_label(ui: &Ui, labels: Vec) -> f32 { } /// Where a row `width` wide puts its sample, after the name column: room for the widest name -/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`] and the star for the sample or -/// [`NAME_SHARE`] of the row for the name. Without samples the name runs to the star. +/// (`widest`) and a gap, as far as that leaves [`SAMPLE_W`], the Show Similar Fonts button and the +/// star for the sample or [`NAME_SHARE`] of the row for the name. Without samples the name runs to +/// the Show Similar Fonts button. fn name_column(width: f32, widest: f32, samples: bool) -> f32 { if !samples { - return width - STAR; + return width - SIMILAR - STAR; } - (DISCLOSURE + widest + NAME_GAP).min((width - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE)) + (DISCLOSURE + widest + NAME_GAP).min((width - SIMILAR - STAR - 2.0 - SAMPLE_W).max(width * NAME_SHARE)) } /// The disclosure triangle of a family with several styles; whether the pointer is on it. @@ -1293,6 +1328,18 @@ fn star_cell(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, (on, hi resp.interact_pointer_pos().is_some_and(|pos| star.contains(pos)) } +/// The Show Similar Fonts button before a family's star, shown when the row is hovered or +/// highlighted, or is the family the list is ordered by; whether the pointer hovers it, and whether +/// it presses it. +fn similar_cell(p: &egui::Painter, resp: &egui::Response, cell: egui::Rect, (on, highlighted): (bool, bool), t: &Tokens) -> (bool, bool) { + let hot = resp.hover_pos().is_some_and(|pos| cell.contains(pos)); + if on || highlighted || resp.hovered() { + let color = if on || hot { t.accent } else { t.text_dim }; + p.text(cell.center(), egui::Align2::CENTER_CENTER, "≈", egui::FontId::proportional(13.0), color); + } + (hot, resp.interact_pointer_pos().is_some_and(|pos| cell.contains(pos))) +} + /// A heading row (Recent Fonts, Fonts), which cannot preview or apply a font. fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) { let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::hover()); @@ -1304,6 +1351,35 @@ fn heading_row(ui: &mut Ui, row_h: f32, label: &str, t: &Tokens) { ui.painter_at(rect).text(rect.left_center() + vec2(4.0, 0.0), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(11.0), t.text_dim); } +/// The row the list scrolls to this frame, and how it aligns it. Opening, the list shows the recent +/// section even when the current family is farther down the list, else centres the current font; +/// key presses keep the highlight in view. Show Similar Fonts goes to the first row, the family it +/// orders by, and clearing it goes back to that family, highlighted. +fn scroll_target(st: &mut MenuState, rows: &[Row], opening: bool, keyed: bool) -> Option<(usize, Option)> { + if st.similar_moved.take().is_some() { + return match st.similar { + Some(_) => Some((0, Some(egui::Align::TOP))), + None => st.highlight.map(|i| (i, Some(egui::Align::Center))), + }; + } + if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) { + return Some((0, Some(egui::Align::TOP))); + } + st.highlight.filter(|_| opening || keyed).map(|i| (i, opening.then_some(egui::Align::Center))) +} + +/// The Show Similar Fonts button of family `f`'s row `i` before its star (`star`); whether the +/// pointer presses it. A click on it asks for the list ordered by likeness to `f`. +fn similar_button(p: &egui::Painter, resp: &egui::Response, star: egui::Rect, f: &str, (st, i): (&MenuState, usize), t: &Tokens) -> (bool, bool) { + let cell = egui::Rect::from_min_max(egui::pos2(star.min.x - SIMILAR, star.min.y), egui::pos2(star.min.x, star.max.y)); + let ordering = st.similar.as_deref().is_some_and(|s| s.eq_ignore_ascii_case(f)); + let (hot, pressed) = similar_cell(p, resp, cell, (ordering, st.highlight == Some(i)), t); + if hot { + resp.clone().on_hover_text(tl!("Show Similar Fonts")); + } + (pressed, resp.clicked() && pressed) +} + /// The rows of the open menu in `range`, the ones in view: the menu's one scrolling part, under /// the search field and filters (#555). fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Option<&str>, look: MenuLook) -> Option { @@ -1327,19 +1403,14 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h)); ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none()); }; - // Open at the recent section even when the current family is farther down the list. - // Otherwise centre the current font; subsequent key presses keep the highlight in view. - if opening && matches!(rows.first(), Some(Row::Heading("Recent Fonts"))) { - scroll_to(ui, 0, Some(egui::Align::TOP)); - } else if let Some(i) = st.highlight - && (opening || keyed) - { - scroll_to(ui, i, opening.then_some(egui::Align::Center)); + if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) { + scroll_to(ui, i, align); } let mut chosen: Option<(String, Option)> = None; let mut hovered: Option = None; let mut toggled: Option = None; let mut starred: Option = None; + let mut similar: Option = None; for i in range { let Some(row) = rows.get(i) else { continue }; if let Row::Heading(label) = row { @@ -1379,6 +1450,12 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio starred = Some(f.clone()); } } + let mut on_similar = false; + if let Row::Family(f) = row { + let (pressed, clicked) = similar_button(&p, &resp, star, f, (&*st, i), &t); + on_similar = pressed; + similar = similar.or(clicked.then(|| f.clone())); + } let indent = if row.style().is_some() { DISCLOSURE + STYLE_INDENT } else { DISCLOSURE }; let name_w = name_column(rect.width(), widest, look.samples); let name_rect = egui::Rect::from_min_max(rect.min + vec2(indent, 0.0), egui::pos2(rect.min.x + name_w - 4.0, rect.max.y)); @@ -1390,7 +1467,7 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio }; ui.painter_at(name_rect).text(name_rect.left_center(), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(NAME_SIZE), t.text); // The sample takes the row's whole height. - let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(STAR + 2.0, 0.0)); + let sample_rect = egui::Rect::from_min_max(rect.min + vec2(name_w, 0.0), rect.max - vec2(SIMILAR + STAR + 2.0, 0.0)); if look.samples { // The paper is drawn while the sample is still rendering, and for a family whose sample fails. let area = sample_area(ui, sample_rect, ink, PAPER_INSET); @@ -1398,10 +1475,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio paint_sample(ui, area, &tex, ink); } } - if resp.clicked() && !on_triangle && !on_star { + if resp.clicked() && !on_triangle && !on_star && !on_similar { chosen = row.pick(); } } + if let Some(f) = similar { + // The rows are ordered again next frame, which highlights `f` and scrolls to it. + st.similar_moved = Some(f.clone()); + st.similar = Some(f); + return None; + } if let Some(f) = toggled { if st.expanded.contains(&f) { st.expanded.retain(|e| *e != f); diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 11a66cab00..670418a420 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -64,15 +64,15 @@ fn the_scroll_bar_leaves_the_stars_clear() { /// In a wide row the sample starts after the widest name and a gap, not halfway along, even for a /// name wider than the menu widens itself for; the sample keeps its room, and a row too narrow for -/// both gives the name half of it. Without samples the name runs to the star. +/// both gives the name half of it. Without samples the name runs to the Show Similar Fonts button. #[test] fn the_sample_starts_after_the_widest_name() { - use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, STAR, name_column}; + use super::{DISCLOSURE, NAME_GAP, NAME_MAX, SAMPLE_W, SIMILAR, STAR, name_column}; assert_eq!(name_column(500.0, 100.0, true), DISCLOSURE + 100.0 + NAME_GAP); assert_eq!(name_column(600.0, NAME_MAX + 80.0, true), DISCLOSURE + NAME_MAX + 80.0 + NAME_GAP); - assert_eq!(name_column(600.0, 1000.0, true), 600.0 - STAR - 2.0 - SAMPLE_W); + assert_eq!(name_column(600.0, 1000.0, true), 600.0 - SIMILAR - STAR - 2.0 - SAMPLE_W); assert_eq!(name_column(200.0, 100.0, true), 100.0); - assert_eq!(name_column(500.0, 100.0, false), 500.0 - STAR); + assert_eq!(name_column(500.0, 100.0, false), 500.0 - SIMILAR - STAR); } /// The widest label is the widest one laid out, though it has fewer characters than others, or @@ -1055,3 +1055,79 @@ fn a_menu_items_sample_follows_show_samples_on_white() { assert!(!shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default())), "no sample"); assert!(shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.fill == super::SAMPLE_PAPER && r.rect == slot)), "the slot is white"); } + +/// The center of the first text shape whose text passes `wanted`. +fn text_at(shapes: &[egui::epaint::ClippedShape], wanted: impl Fn(&str) -> bool) -> Option { + shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(t) if wanted(t.galley.text()) => Some(t.visual_bounding_rect().center()), + _ => None, + }) +} + +/// Show Similar Fonts: the ≈ button of a family's row orders the listed families by likeness to +/// it, that family first and highlighted, without the Recent Fonts section and without picking a +/// font; the ≈ chip under the filters puts the menu's order back, and so does opening the menu +/// again. +#[test] +fn show_similar_fonts_orders_the_list_by_likeness() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let recent = vec!["JetBrains Mono".to_string()]; + let ctx = egui::Context::default(); + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0)); + let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() }; + let mut st = super::MenuState::default(); + let picks = std::cell::RefCell::new(vec![]); + let mut frame = |events: Vec, st: &mut super::MenuState| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + picks.borrow_mut().extend(super::list_of(&mut child, &db, egui::Id::unique("similar"), st, "Inter", None, look).inner); + }); + out.textures_delta.clear(); + out.shapes + }; + let click = |frame: &mut dyn FnMut(Vec, &mut super::MenuState) -> Vec, + st: &mut super::MenuState, + pos: egui::Pos2| { + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(vec![egui::Event::PointerMoved(pos)], st); + frame(vec![button(true)], st); + frame(vec![button(false)], st); + frame(vec![], st) + }; + let families = |st: &super::MenuState| st.rows.iter().filter_map(super::Row::family).map(str::to_string).collect::>(); + let row_of = |st: &super::MenuState, family: &str| st.rows.iter().position(|r| r.family() == Some(family) && r.style().is_none()); + let shapes = frame(vec![], &mut st); + let menu_order = families(&st); + assert_eq!(st.rows.first(), Some(&super::Row::Heading("Recent Fonts"))); + // A hovered row shows its ≈ button: here Source Serif 4's, not the current family's (Inter). + let name = text_at(&shapes, |t| t == "Source Serif 4").expect("Source Serif 4 is listed"); + let shapes = frame(vec![egui::Event::PointerMoved(name)], &mut st); + let button = shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == "≈" && (t.visual_bounding_rect().center().y - name.y).abs() < 2.0 => { + Some(t.visual_bounding_rect().center()) + } + _ => None, + }) + .expect("the hovered row shows ≈"); + let shapes = click(&mut frame, &mut st, button); + assert_eq!(st.similar.as_deref(), Some("Source Serif 4")); + assert_eq!(families(&st), db.similar_families("Source Serif 4", &db.menu_family_list())); + assert_eq!(families(&st).first().map(String::as_str), Some("Source Serif 4")); + assert!(!st.rows.iter().any(|r| matches!(r, super::Row::Heading(_))), "no Recent Fonts section: {:?}", st.rows); + assert_eq!(st.highlight, Some(0)); + assert!(!picks.borrow().iter().any(|p| matches!(p, super::FontPick::Chosen(..))), "no font picked: {:?}", picks.borrow()); + // The chip under the filters clears it, and the family it ordered by stays highlighted. + let chip = text_at(&shapes, |t| t.starts_with("≈ Source Serif 4")).expect("the chip names the family"); + click(&mut frame, &mut st, chip); + assert_eq!(st.similar, None); + assert_eq!(families(&st), menu_order); + assert_eq!(st.highlight, row_of(&st, "Source Serif 4")); + // Opening the menu again lists in the menu's order too. + st.similar = Some("Inter".into()); + st.last = 0; + frame(vec![], &mut st); + assert_eq!((st.similar.as_deref(), families(&st)), (None, menu_order)); +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 60518dcd2d..d54ea0178a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -681,11 +681,12 @@ const MESSAGE_DEPTH: usize = 5; /// Translate a status or error message for display (see the module docs). Unknown messages, and /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as -/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a -/// symbol's name), stay as they are. A part that starts with `{` is translated only when it is a -/// whole message with an exact entry. A part that starts with `[` is translated when it has an -/// exact entry, such as `[x, y] (two numbers)`, or when it fits a template that starts with `[` -/// and an index of digits, such as an effect's refusal ``[0] `id`: {why}``. +/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”`, `'…'` or backticks, such as a +/// symbol's or a script property's name, and an `{ident}` placeholder's value, a script identifier), +/// stay as they are. A part that starts with `{` is translated only when it is a whole message with +/// an exact entry. A part that starts with `[` is translated when it has an exact entry, such as +/// `[x, y] (two numbers)`, or when it fits a template that starts with `[` and an index of digits, +/// such as an effect's refusal ``[0] `id`: {why}``. pub fn message(lang: Lang, s: &str) -> String { message_at(lang, s, MESSAGE_DEPTH) } @@ -701,9 +702,15 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); let Some(template) = forms.get(form) else { return s.to_string() }; - let quoted = |v: &str| [('"', '"'), ('“', '”'), ('`', '`')].iter().any(|(a, b)| s.contains(&format!("{a}{v}{b}"))); + // A value is quoted when quotes surround it at its own place in `s`. The same text quoted at + // another place in `s` (a property named like the reason given for it) does not count. + let quoted = |v: &str| { + let at = (v.as_ptr() as usize).checked_sub(s.as_ptr() as usize); + let Some((before, after)) = at.and_then(|at| Some((s.get(..at)?, s.get(at + v.len()..)?))) else { return false }; + [('"', '"'), ('“', '”'), ('\'', '\''), ('`', '`')].iter().any(|(a, b)| before.ends_with(*a) && after.starts_with(*b)) + }; let nested = |v: &str| { - if depth <= 1 || quoted(v) { + if depth <= 1 || v.is_empty() || quoted(v) { v.to_string() } else if v.starts_with('{') { exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string()) @@ -719,6 +726,7 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures .map(|(k, v)| match (&liquify, k) { (Some((tool, _)), "_1") => (k, tool.clone()), (Some((_, kinds)), "_2") => (k, kinds.clone()), + (_, "ident") => (k, v.to_string()), _ => (k, nested(v)), }) .collect(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index c18df53992..d6729a36e8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1288,6 +1288,8 @@ font-technology Variable Променливи Font Family & Style Семейство и стил шрифтове Font Family, Style & Size Семейство, стил и размер на шрифта Font List Списък с шрифтове + Show Similar Fonts Показване на подобни шрифтове + Clear Similar Fonts Изчистване на подобните шрифтове Font Preview Size Размер за преглед на шрифта Font Size Размер на шрифта Variable Font Променлив шрифт @@ -3176,6 +3178,8 @@ digits Malayalam Малаялам Search All Търсене във всички Search commands and tools Търсене на команди и инструменти Search commands and tools… Търсене на команди и инструменти… + Recent Commands Последни команди + No recent commands Няма последни команди Search Commands… Търсене на команди… Secondary Вторичен Section Symbol Символ за раздел @@ -5031,6 +5035,10 @@ axis Both И двете Em Box Квадратна касетка (Em Box) x-Height Височина на x ICF Box Касетка ICF + Show Sample Показване на образец + Hide Sample Скриване на образец + Max Ascent/Descent Макс. височина нагоре/надолу + Max Ascender Макс. възходящ елемент @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` е референцията за стъпка {r}, която се разрешава само от `run` и `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` трябва да бъде масив от идентификатори на обекти, а не {v} @msg `colors` must be an array of colors, not {v} `colors` трябва да бъде масив от цветове, а не {v} @@ -5896,7 +5904,7 @@ theme Appearance Външен вид @msg Unknown dimension orientation Непозната ориентация на размера @msg Unknown dimension style Непознат стил на размера @msg Unknown unit Непозната единица - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни остават отворени. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Затваря кръговите краища на отворени профили. При частично завъртане срязаните страни също се затварят. # Strings added with Drop Shadow Darkness, Isolate Selected Object, Pencil Keep selected, Sample Color from Screen, Tritanopia proofing, Panels Except Tools and Control Darkness Затъмняване @@ -6751,6 +6759,24 @@ breakText Glyphs Глифи # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разширяване на тиретата в пътища @msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Допирателна окръжност… + Tangent Circle Допирателна окръжност + Circle: Окръжност: +@msg `ids` names an object twice `ids` посочва обект два пъти +@msg select two or three paths or compound paths изберете два или три пътя или съставни пътя +@msg `radius` must be from 0.01 to 1000000 pt `radius` трябва да е от 0.01 до 1000000 pt +@msg two shapes need a `radius` две форми изискват `radius` +@msg three shapes set the radius themselves: leave `radius` out три форми сами задават радиуса: пропуснете `radius` +@msg `circle` must be from 0 to 64 `circle` трябва да е от 0 до 64 +@msg a shape has no outline една от формите няма контур +@msg the shapes are too complex: at most 2000 segments in all формите са твърде сложни: общо най-много 2000 сегмента +@msg these shapes take too long to search търсенето за тези форми отнема твърде дълго +@msg more than 64 circles touch these shapes: they may touch along a whole curve повече от 64 окръжности докосват тези форми: може да ги докосват по цяла крива +@msg no circle touches these shapes никоя окръжност не докосва тези форми +@msg `circle` is past the last circle found ({found}) `circle` е след последната намерена окръжност ({found}) +@msg object {value} is not a path or compound path обект {value} не е път или съставен път +@msg these shapes are too small to measure тези форми са твърде малки, за да бъдат измерени # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Инструменти за документи Save a Timestamped Copy Запазване на копие с дата и час @@ -6805,7 +6831,7 @@ breakText Glyphs Глифи @msg stroke cannot be set on a symbol instance stroke не може да се задава за екземпляр на символ @msg fill on a symbol instance must be a solid color or none fill на екземпляр на символ трябва да е плътен цвят или none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} не може да се задава за изображение без ефект „Конвертиране в фигура“ или „Преобразуване на обекта в контур“ -@msg pass newName, registration, exportType, nineSlice and/or type задайте newName, registration, exportType, nineSlice и/или type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid задайте newName, registration, exportType, nineSlice, type и/или alignToPixelGrid Text Flow Поток на текста By Rows По редове By Columns По колони diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3484e06bdf..a52f3e4834 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1678,6 +1678,10 @@ digits Malayalam Malajalam Em Box Em okvir x-Height Visina malih slova ICF Box ICF okvir + Show Sample Prikaži uzorak + Hide Sample Sakrij uzorak + Max Ascent/Descent Maks. visina gore/dolje + Max Ascender Maks. gornji produžetak Copy Color Value (Hex) Kopiraj vrijednost boje (hex) Create New Swatch… Kreiraj novi uzorak boje… Name 40% Naziv 40% @@ -3594,6 +3598,8 @@ theme Appearance Izgled Find Font Files Pronađi datoteke fontova Add Font Files Dodaj datoteke fontova Font List Lista fontova + Show Similar Fonts Prikaži slične fontove + Clear Similar Fonts Očisti slične fontove Fonts in Document Fontovi u dokumentu Refresh Font List Osvježi listu fontova Replace Font Zamijeni font @@ -4370,6 +4376,8 @@ font-technology Variable Varijabilni Saving Čuvanje Saving {} Čuvanje {} Search commands and tools… Pretraži naredbe i alate… + Recent Commands Nedavne naredbe + No recent commands Nema nedavnih naredbi Dashed Line Isprekidana linija Panel menu Meni panela Unembed… Poništi ugrađivanje… @@ -5946,7 +5954,7 @@ mark-style Japanese Japanski @msg Unknown dimension orientation Nepoznata orijentacija kote @msg Unknown dimension style Nepoznat stil kote @msg Unknown unit Nepoznata jedinica - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zadržavaju otvorene rezane strane. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Zatvori kružne krajeve otvorenih profila. Djelimična izvlačenja zatvaraju i svoje rezane strane. @msg span must be "object" or "selection", got {v} span mora biti "object" ili "selection", dobiveno {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" postavlja `gradient`, a ne uzorak boje @msg span: "selection" places a gradient: give `gradient` span: "selection" postavlja gradijent: navedite `gradient` @@ -6803,6 +6811,24 @@ shape Open Otvoren # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Proširi crtice u putanje @msg select paths with dashed strokes to expand odaberite putanje s isprekidanim potezom za proširivanje +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Tangentna kružnica… + Tangent Circle Tangentna kružnica + Circle: Kružnica: +@msg `ids` names an object twice `ids` navodi objekat dvaput +@msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje +@msg `radius` must be from 0.01 to 1000000 pt `radius` mora biti od 0.01 do 1000000 pt +@msg two shapes need a `radius` dva oblika trebaju `radius` +@msg three shapes set the radius themselves: leave `radius` out tri oblika sama određuju poluprečnik: izostavite `radius` +@msg `circle` must be from 0 to 64 `circle` mora biti od 0 do 64 +@msg a shape has no outline oblik nema obris +@msg the shapes are too complex: at most 2000 segments in all oblici su previše složeni: najviše 2000 segmenata ukupno +@msg these shapes take too long to search pretraga za ove oblike traje predugo +@msg more than 64 circles touch these shapes: they may touch along a whole curve više od 64 kružnice dodiruje ove oblike: možda ih dodiruju duž cijele krivulje +@msg no circle touches these shapes nijedna kružnica ne dodiruje ove oblike +@msg `circle` is past the last circle found ({found}) `circle` je iza posljednje pronađene kružnice ({found}) +@msg object {value} is not a path or compound path objekat {value} nije putanja ni složena putanja +@msg these shapes are too small to measure ovi oblici su premali za mjerenje # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Alati za dokument Save a Timestamped Copy Sačuvaj kopiju s datumom i vremenom @@ -6857,7 +6883,7 @@ shape Open Otvoren @msg stroke cannot be set on a symbol instance stroke se ne može postaviti na instancu simbola @msg fill on a symbol instance must be a solid color or none fill instance simbola mora biti puna boja ili none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} se ne može postaviti na sliku bez efekta „Pretvori u oblik“ ili „Objekat u obrisu“ -@msg pass newName, registration, exportType, nineSlice and/or type navedite newName, registration, exportType, nineSlice i/ili type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid navedite newName, registration, exportType, nineSlice, type i/ili alignToPixelGrid Text Flow Tok teksta By Rows Po redovima By Columns Po kolonama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b1d0ea361a..7ea9cc24e2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -754,7 +754,7 @@ antiAlias Sharp Nítid Close Panel Tanca el panell Close Path Tanca el traçat Close paths when ends are within: Tanca els traçats quan els extrems siguin a menys de: - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Tanca els extrems circulars dels perfils oberts. Els escombrats parcials mantenen oberts els costats tallats. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Tanca els extrems circulars dels perfils oberts. Els escombrats parcials també tanquen els costats tallats. Closed Tancat Closing bracket with no opening one Delimitador de tancament sense un d’obertura Clumped Agrupat @@ -1805,6 +1805,8 @@ digits Malayalam Malaiàlam Font Family, Style & Size Família, estil i mida de tipus de lletra Font Family: Família de tipus de lletra: Font List Llista de tipus de lletra + Show Similar Fonts Mostra tipus de lletra semblants + Clear Similar Fonts Esborra els tipus de lletra semblants Font Preview Size Mida de previsualització del tipus de lletra Font Size Mida del tipus de lletra Font Style: Estil de tipus de lletra: @@ -2662,7 +2664,8 @@ digits Malayalam Malaiàlam Minimal Mínim Minimize Minimitza Minimum Mínim - Minimum must not exceed Desired, nor Desired Maximum. El mínim no pot superar el desitjat ni el màxim desitjat. + Minimum must not exceed Desired, nor Desired Maximum. El mínim no pot superar el desitjat, ni el desitjat el màxim. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: el mínim no pot superar el desitjat, ni el desitjat el màxim Minus Back Resta al darrere Minus Front Resta al davant Mirror Reflexa @@ -4103,6 +4106,8 @@ digits Malayalam Malaiàlam Search All Cerca a tot Search commands and tools Cerca ordres i eines Search commands and tools… Cerca ordres i eines… + Recent Commands Ordres recents + No recent commands No hi ha ordres recents Search Commands… Cerca ordres… Search Fonts Folder Cerca a la carpeta de tipus de lletra Searching… Cercant… @@ -5697,6 +5702,44 @@ digits Malayalam Malaiàlam @msg $.evalFile requires a file path $.evalFile requereix un camí de fitxer @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el temps d'espera ha de ser un nombre finit de mil·lisegons, 0 o més @msg $.evalFile: takes a file path and a timeout $.evalFile: rep un camí de fitxer i un temps d'espera +@msg assignment to a constant binding assignació a un enllaç constant +@msg invalid array length longitud de matriu no vàlida +@msg array literal too long el literal de matriu és massa llarg +@msg the value is not a function el valor no és una funció +@msg apply was called on a value that is not a function s'ha cridat apply sobre un valor que no és una funció +@msg the argument list is not an object la llista d'arguments no és un objecte +@msg too many arguments massa arguments +@msg the value is not a constructor el valor no és un constructor +@msg cannot convert the object to a primitive value no es pot convertir l'objecte en un valor primitiu +@msg cannot convert undefined or null to an object no es pot convertir undefined ni null en un objecte +@msg the right side of 'in' is not an object el costat dret de 'in' no és un objecte +@msg the right side of 'instanceof' is not a function el costat dret de 'instanceof' no és una funció +@msg the function's prototype is not an object el prototip de la funció no és un objecte +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} no està definit +@msg cannot read property '{key}' of {base} no es pot llegir la propietat '{key}' de {base} +@msg cannot set property '{key}' of {base} no es pot establir la propietat '{key}' de {base} +@msg cannot read a property of {base} no es pot llegir cap propietat de {base} +@msg cannot set a property of {base} no es pot establir cap propietat de {base} +@msg cannot define property '{key}': {why} no es pot definir la propietat '{key}': {why} +@msg cannot assign to property '{key}': {why} no es pot assignar a la propietat '{key}': {why} +@msg cannot delete property '{key}' no es pot suprimir la propietat '{key}' +@msg cannot declare function {ident} no es pot declarar la funció {ident} +@msg invalid assignment target destinació d'assignació no vàlida +@msg the array's length is read-only la longitud de la matriu és només de lectura +@msg the property cannot be redefined la propietat no es pot redefinir +@msg the object is not extensible l'objecte no és extensible +@msg the length cannot be redefined la longitud no es pot redefinir +@msg it is read-only és només de lectura +@msg an element cannot be deleted no es pot suprimir un element +@msg it has only a getter només té un getter +@msg the value is a primitive el valor és primitiu @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línia {line}, columna {column} de {file}: {e} (llançat) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: línia {line}, columna {column}: {e} (llançat) @msg {name}: {e} (thrown) {name}: {e} (llançat) @@ -5833,6 +5876,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg every numbered name for {name} is taken in the document's folder tots els noms numerats per a {name} estan ocupats a la carpeta del document @msg every search thread stopped on an internal error (please report this bug) tots els fils de cerca s’han aturat per un error intern (informeu d’aquest error) @msg Expand Appearance: the selection has a basic appearance Expandeix l’aparença: la selecció té una aparença bàsica +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alguns efectes ràster no s’han convertit en imatges: ocuparien més de 1.024 imatges o 256 megapíxels en total @msg Expand: no brush strokes selected Expandeix: no s’ha seleccionat cap traç de pinzell @msg Expand: no gradient fills Expandeix: no hi ha farciments de degradat @msg Expand: nothing to expand Expandeix: no hi ha res per expandir @@ -7023,6 +7067,10 @@ theme Appearance Aparença Em Box Caixa em x-Height Alçada de la x ICF Box Caixa ICF + Show Sample Mostra l'exemple + Hide Sample Amaga l'exemple + Max Ascent/Descent Alçada/profunditat màx. + Max Ascender Ascendent màx. # Average & Join (Object › Path, Cmd+Alt+Shift+J). Average & Join… Mitjana i unió… Average & Join Mitjana i unió @@ -7415,6 +7463,24 @@ breakText Glyphs Glifs # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandeix els guions en camins @msg select paths with dashed strokes to expand seleccioneu camins amb traç discontinu per expandir +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Cercle tangent… + Tangent Circle Cercle tangent + Circle: Cercle: +@msg `ids` names an object twice `ids` indica un objecte dues vegades +@msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos +@msg `radius` must be from 0.01 to 1000000 pt `radius` ha de ser de 0.01 a 1000000 pt +@msg two shapes need a `radius` dues formes necessiten un `radius` +@msg three shapes set the radius themselves: leave `radius` out tres formes fixen el radi per si mateixes: ometeu `radius` +@msg `circle` must be from 0 to 64 `circle` ha de ser de 0 a 64 +@msg a shape has no outline una forma no té contorn +@msg the shapes are too complex: at most 2000 segments in all les formes són massa complexes: com a màxim 2000 segments en total +@msg these shapes take too long to search la cerca triga massa amb aquestes formes +@msg more than 64 circles touch these shapes: they may touch along a whole curve més de 64 cercles toquen aquestes formes: potser les toquen al llarg de tota una corba +@msg no circle touches these shapes cap cercle no toca aquestes formes +@msg `circle` is past the last circle found ({found}) `circle` passa de l’últim cercle trobat ({found}) +@msg object {value} is not a path or compound path l’objecte {value} no és un camí ni un camí compost +@msg these shapes are too small to measure aquestes formes són massa petites per mesurar-les # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Eines del document Save a Timestamped Copy Desa una còpia amb data i hora @@ -7469,7 +7535,7 @@ breakText Glyphs Glifs @msg stroke cannot be set on a symbol instance stroke no es pot definir en una instància de símbol @msg fill on a symbol instance must be a solid color or none el fill d’una instància de símbol ha de ser un color sòlid o none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} no es pot definir en una imatge sense l’efecte Converteix en forma o Contorneja l’objecte -@msg pass newName, registration, exportType, nineSlice and/or type indiqueu newName, registration, exportType, nineSlice i/o type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indiqueu newName, registration, exportType, nineSlice, type i/o alignToPixelGrid Text Flow Flux del text By Rows Per files By Columns Per columnes diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index cbb2c5b702..01d88af108 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -92,17 +92,19 @@ impl Template { /// The placeholder values if `s` is an instance of this template. fn captures<'a>(&self, s: &'a str) -> Option> { let mut out = Vec::new(); - match_pieces(&self.pieces, s, self.counted, &mut out).then_some(out) + match_pieces(&self.pieces, s, self.counted, &mut out, None).then_some(out) } } /// Match `s` against `pieces`, a placeholder taking the shortest non-empty text that lets the -/// rest match (the last one takes what remains). With `counted`, `{n}` takes only a count. A -/// placeholder that occurs twice takes the same text both times. -fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>) -> bool { +/// rest match (the last one takes what remains). A placeholder between two of the same quote +/// (`'{key}'`, `"{key}"` or `` `{key}` ``) may also take no text, as for a property named by the +/// empty string. With `counted`, `{n}` takes only a count. A placeholder that occurs twice takes +/// the same text both times. `before` is the last character of the text piece before `pieces`. +fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>, before: Option) -> bool { let Some((first, rest)) = pieces.split_first() else { return s.is_empty() }; match first { - Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out)), + Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out, t.chars().last())), Piece::Hole(name) => { let earlier = out.iter().find(|(n, _)| *n == name.as_str()).map(|&(_, v)| v); let fits = |value: &str| (!(counted && name == "n") || value.parse::().is_ok()) && earlier.is_none_or(|e| e == value); @@ -114,7 +116,19 @@ fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mu return true; }; let Piece::Text(next) = next else { return false }; - // Every place the next literal occurs, nearest first (the hole is never empty). + let quoted = before.is_some_and(|q| matches!(q, '\'' | '"' | '`') && next.starts_with(q)); + if quoted + && fits("") + && let Some(tail) = s.strip_prefix(next.as_str()) + { + let mark = out.len(); + out.push((name.as_str(), "")); + if match_pieces(after, tail, counted, out, next.chars().last()) { + return true; + } + out.truncate(mark); + } + // Every other place the next literal occurs, nearest first. let mut from = s.chars().next().map_or(1, char::len_utf8); while let Some(at) = s.get(from..).and_then(|tail| tail.find(next.as_str())).map(|i| i + from) { let (Some(value), Some(tail)) = (s.get(..at), s.get(at + next.len()..)) else { return false }; @@ -124,7 +138,7 @@ fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mu } let mark = out.len(); out.push((name.as_str(), value)); - if match_pieces(after, tail, counted, out) { + if match_pieces(after, tail, counted, out, next.chars().last()) { return true; } out.truncate(mark); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 65d15971fa..a42cb904d3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1749,6 +1749,10 @@ digits Malayalam Malajálamské Em Box Čtverčík x-Height Výška x ICF Box Rámeček ICF + Show Sample Zobrazit ukázku + Hide Sample Skrýt ukázku + Max Ascent/Descent Max. výška/hloubka + Max Ascender Max. horní dotah Copy Color Value (Hex) Kopírovat hodnotu barvy (hex) Create New Swatch… Vytvořit novou položku vzorníku… Name 40% Název 40 % @@ -3697,6 +3701,8 @@ theme Appearance Motiv Find Font Files Najít soubory písem Add Font Files Přidat soubory písem Font List Seznam písem + Show Similar Fonts Zobrazit podobná písma + Clear Similar Fonts Zrušit podobná písma Fonts in Document Písma v dokumentu Refresh Font List Obnovit seznam písem Replace Font Nahradit písmo @@ -4475,6 +4481,8 @@ font-technology Variable Variabilní Saving Ukládání Saving {} Ukládání {} Search commands and tools… Hledat příkazy a nástroje… + Recent Commands Nedávné příkazy + No recent commands Žádné nedávné příkazy Dashed Line Čárkovaná čára Panel menu Nabídka panelu Unembed… Zrušit vložení… @@ -4785,6 +4793,31 @@ imageTrace Outline Obrys @msg $.evalFile requires a file path $.evalFile vyžaduje cestu k souboru @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: časový limit musí být konečný počet milisekund, 0 nebo více @msg $.evalFile: takes a file path and a timeout $.evalFile: přijímá cestu k souboru a časový limit +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} není definováno +@msg cannot read property '{key}' of {base} nelze číst vlastnost '{key}' hodnoty {base} +@msg cannot set property '{key}' of {base} nelze nastavit vlastnost '{key}' hodnoty {base} +@msg cannot read a property of {base} nelze číst vlastnost hodnoty {base} +@msg cannot set a property of {base} nelze nastavit vlastnost hodnoty {base} +@msg cannot define property '{key}': {why} nelze definovat vlastnost '{key}': {why} +@msg cannot assign to property '{key}': {why} nelze přiřadit do vlastnosti '{key}': {why} +@msg cannot delete property '{key}' nelze odstranit vlastnost '{key}' +@msg cannot declare function {ident} nelze deklarovat funkci {ident} +@msg invalid assignment target neplatný cíl přiřazení +@msg the array's length is read-only délka pole je jen pro čtení +@msg the property cannot be redefined vlastnost nelze znovu definovat +@msg the object is not extensible objekt nelze rozšiřovat +@msg the length cannot be redefined délku nelze znovu definovat +@msg it is read-only je jen pro čtení +@msg an element cannot be deleted prvek nelze odstranit +@msg it has only a getter má pouze getter +@msg the value is a primitive hodnota je primitivní @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: řádek {line}, sloupec {column} v {file}: {e} (vyvolána výjimka) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: řádek {line}, sloupec {column}: {e} (vyvolána výjimka) @msg {name}: {e} (thrown) {name}: {e} (vyvolána výjimka) @@ -4891,6 +4924,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu @msg Downloaded {what} Staženo: {what} @msg Expand Appearance: the selection has a basic appearance Rozložit vzhled: výběr má základní vzhled +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all některé rastrové efekty nebyly převedeny na obrazy: zabraly by více než 1 024 obrazů nebo celkem 256 megapixelů @msg Expand: no brush strokes selected Rozložit: nejsou vybrány žádné tahy štětcem @msg Expand: no gradient fills Rozložit: žádné přechodové výplně @msg Expand: nothing to expand Rozložit: není co rozložit @@ -6330,7 +6364,7 @@ mark-style Japanese Japonské @msg Unknown dimension style Neznámý styl kóty @msg Unknown unit Neznámá jednotka # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Uzavře kruhové konce otevřených profilů. Boční řezy částečného otočení zůstávají otevřené. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Uzavře kruhové konce otevřených profilů. Boční řezy částečného otočení se také uzavřou. @msg span must be "object" or "selection", got {v} span musí být "object" nebo "selection", ne {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" umísťuje `gradient`, ne vzorník @msg span: "selection" places a gradient: give `gradient` span: "selection" umísťuje přechod: zadejte `gradient` @@ -6482,6 +6516,7 @@ mark-style Japanese Japonské Single Word Justification: Zarovnání jednoho slova: Full Justify Zarovnat do bloku Minimum must not exceed Desired, nor Desired Maximum. Minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum Justification Zarovnání do bloku Add filters from the list above Přidejte filtry ze seznamu výše Add to Stack Přidat na zásobník @@ -7419,6 +7454,24 @@ breakText Glyphs Glyfy # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozložit čárky na cesty @msg select paths with dashed strokes to expand vyberte cesty s čárkovaným tahem k rozložení +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Tečná kružnice… + Tangent Circle Tečná kružnice + Circle: Kružnice: +@msg `ids` names an object twice `ids` uvádí některý objekt dvakrát +@msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty +@msg `radius` must be from 0.01 to 1000000 pt `radius` musí být od 0.01 do 1000000 pt +@msg two shapes need a `radius` dva tvary potřebují `radius` +@msg three shapes set the radius themselves: leave `radius` out tři tvary určují poloměr samy: vynechte `radius` +@msg `circle` must be from 0 to 64 `circle` musí být od 0 do 64 +@msg a shape has no outline tvar nemá obrys +@msg the shapes are too complex: at most 2000 segments in all tvary jsou příliš složité: celkem nejvýše 2000 segmentů +@msg these shapes take too long to search hledání pro tyto tvary trvá příliš dlouho +@msg more than 64 circles touch these shapes: they may touch along a whole curve těchto tvarů se dotýká více než 64 kružnic: mohou se jich dotýkat podél celé křivky +@msg no circle touches these shapes žádná kružnice se těchto tvarů nedotýká +@msg `circle` is past the last circle found ({found}) `circle` je za poslední nalezenou kružnicí ({found}) +@msg object {value} is not a path or compound path objekt {value} není cesta ani složená cesta +@msg these shapes are too small to measure tyto tvary jsou příliš malé na měření # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Nástroje dokumentu Save a Timestamped Copy Uložit kopii s datem a časem @@ -7473,7 +7526,7 @@ breakText Glyphs Glyfy @msg stroke cannot be set on a symbol instance stroke nelze nastavit u instance symbolu @msg fill on a symbol instance must be a solid color or none fill instance symbolu musí být plná barva nebo none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} nelze nastavit u obrazu bez efektu Převést na tvar nebo Převést objekt na obrys -@msg pass newName, registration, exportType, nineSlice and/or type zadejte newName, registration, exportType, nineSlice a/nebo type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid zadejte newName, registration, exportType, nineSlice, type a/nebo alignToPixelGrid Text Flow Tok textu By Rows Po řádcích By Columns Po sloupcích @@ -9068,7 +9121,9 @@ breakText Glyphs Glyfy @msg position must be normal, superscript or subscript position musí být normal, superscript nebo subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position musí být topLeft, topRight, bottomLeft nebo bottomRight @msg positions must be between 0 and 100000 pt positions musí být mezi 0 a 100000 pt +@msg ppi can't be more than {max} for this image ppi nemůže být pro tento obrázek víc než {max} @msg ppi must be a positive number, not {ppi} ppi musí být kladné číslo, ne {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim ponechává pixely obrázku beze změny: vynechte ppi @msg ppi must be between 1 and 2400 ppi musí být mezi 1 a 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` není transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape musí být clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4b565d254d..91f159b3cf 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -91,6 +91,44 @@ @msg $.evalFile requires a file path $.evalFile kræver en filsti @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: tidsgrænsen skal være et endeligt antal millisekunder, 0 eller mere @msg $.evalFile: takes a file path and a timeout $.evalFile: tager en filsti og en tidsgrænse +@msg assignment to a constant binding tildeling til en konstant binding +@msg invalid array length ugyldig arraylængde +@msg array literal too long arrayliteralen er for lang +@msg the value is not a function værdien er ikke en funktion +@msg apply was called on a value that is not a function apply blev kaldt på en værdi, der ikke er en funktion +@msg the argument list is not an object argumentlisten er ikke et objekt +@msg too many arguments for mange argumenter +@msg the value is not a constructor værdien er ikke en konstruktør +@msg cannot convert the object to a primitive value objektet kan ikke konverteres til en primitiv værdi +@msg cannot convert undefined or null to an object undefined eller null kan ikke konverteres til et objekt +@msg the right side of 'in' is not an object højre side af 'in' er ikke et objekt +@msg the right side of 'instanceof' is not a function højre side af 'instanceof' er ikke en funktion +@msg the function's prototype is not an object funktionens prototype er ikke et objekt +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} er ikke defineret +@msg cannot read property '{key}' of {base} egenskaben '{key}' for {base} kan ikke læses +@msg cannot set property '{key}' of {base} egenskaben '{key}' for {base} kan ikke sættes +@msg cannot read a property of {base} en egenskab for {base} kan ikke læses +@msg cannot set a property of {base} en egenskab for {base} kan ikke sættes +@msg cannot define property '{key}': {why} egenskaben '{key}' kan ikke defineres: {why} +@msg cannot assign to property '{key}': {why} der kan ikke tildeles til egenskaben '{key}': {why} +@msg cannot delete property '{key}' egenskaben '{key}' kan ikke slettes +@msg cannot declare function {ident} funktionen {ident} kan ikke erklæres +@msg invalid assignment target ugyldigt tildelingsmål +@msg the array's length is read-only arrayets længde er skrivebeskyttet +@msg the property cannot be redefined egenskaben kan ikke defineres igen +@msg the object is not extensible objektet kan ikke udvides +@msg the length cannot be redefined længden kan ikke defineres igen +@msg it is read-only den er skrivebeskyttet +@msg an element cannot be deleted et element kan ikke slettes +@msg it has only a getter den har kun en getter +@msg the value is a primitive værdien er primitiv @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: linje {line}, kolonne {column} i {file}: {e} (kastet) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: linje {line}, kolonne {column}: {e} (kastet) @msg {name}: {e} (thrown) {name}: {e} (kastet) @@ -4282,6 +4320,10 @@ digits Malayalam Malayalam Em Box Em-felt x-Height x-højde ICF Box ICF-felt + Show Sample Vis eksempel + Hide Sample Skjul eksempel + Max Ascent/Descent Maks. højde/dybde + Max Ascender Maks. overhøjde Copy Color Value (Hex) Kopiér farveværdi (hex) Create New Swatch… Opret ny farveprøve… Name 40% Navn 40% @@ -6055,6 +6097,8 @@ theme Appearance Udseende Find Font Files Find skrifttypefiler Add Font Files Tilføj skrifttypefiler Font List Skrifttypeliste + Show Similar Fonts Vis lignende skrifttyper + Clear Similar Fonts Ryd lignende skrifttyper Fonts in Document Skrifttyper i dokumentet Refresh Font List Opdatér skrifttypeliste Replace Font Erstat skrifttype @@ -6810,6 +6854,8 @@ font-technology Variable Variable Saving Gemmer Saving {} Gemmer {} Search commands and tools… Søg i kommandoer og værktøjer… + Recent Commands Seneste kommandoer + No recent commands Ingen seneste kommandoer Dashed Line Stiplet linje Panel menu Panelmenu Unembed… Ophæv integrering… @@ -7088,6 +7134,7 @@ imageTrace Outline Kontur @msg Divide Objects Below: select exactly one path Opdel objekter nedenunder: markér præcis én kurve @msg Downloaded {what} Downloadede {what} @msg Expand Appearance: the selection has a basic appearance Udvid udseende: markeringen har et grundlæggende udseende +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all nogle rastereffekter blev ikke lavet om til billeder: de ville kræve mere end 1.024 billeder eller i alt 256 megapixel @msg Expand: no brush strokes selected Udvid: ingen penselstrøg er markeret @msg Expand: no gradient fills Udvid: ingen gradientfyld @msg Expand: nothing to expand Udvid: intet at udvide @@ -8343,7 +8390,7 @@ mark-style Japanese Japansk @msg Unknown dimension orientation Ukendt målretning @msg Unknown dimension style Ukendt målstil @msg Unknown unit Ukendt enhed - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Luk de runde ender af åbne profiler. Delvise omdrejninger beholder deres skårne sider åbne. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Luk de runde ender af åbne profiler. Delvise omdrejninger lukker også deres skårne sider. Darkness Mørke Isolate Selected Object Isolér markeret objekt Keep selected Behold markeret @@ -8748,6 +8795,7 @@ swatch Bright Violet Kraftig violet Single Word Justification: Justering af enkeltord: Full Justify Lige margener Minimum must not exceed Desired, nor Desired Maximum. Minimum må ikke overstige Ønsket, og Ønsket ikke Maksimum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum må ikke overstige Ønsket, og Ønsket ikke Maksimum Justification Justering Add filters from the list above Tilføj filtre fra listen ovenfor Add to Stack Tilføj til stak @@ -9457,6 +9505,24 @@ breakText Glyphs Glyffer # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Udvid streger til stier @msg select paths with dashed strokes to expand vælg stier med stiplet streg, der skal udvides +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Tangentcirkel… + Tangent Circle Tangentcirkel + Circle: Cirkel: +@msg `ids` names an object twice `ids` nævner et objekt to gange +@msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier +@msg `radius` must be from 0.01 to 1000000 pt `radius` skal være fra 0.01 til 1000000 pt +@msg two shapes need a `radius` to figurer kræver en `radius` +@msg three shapes set the radius themselves: leave `radius` out tre figurer bestemmer selv radius: udelad `radius` +@msg `circle` must be from 0 to 64 `circle` skal være fra 0 til 64 +@msg a shape has no outline en figur har ingen kontur +@msg the shapes are too complex: at most 2000 segments in all figurerne er for komplekse: højst 2000 segmenter i alt +@msg these shapes take too long to search søgningen tager for lang tid for disse figurer +@msg more than 64 circles touch these shapes: they may touch along a whole curve mere end 64 cirkler rører disse figurer: de rører dem måske langs en hel kurve +@msg no circle touches these shapes ingen cirkel rører disse figurer +@msg `circle` is past the last circle found ({found}) `circle` ligger efter den sidste fundne cirkel ({found}) +@msg object {value} is not a path or compound path objekt {value} er ikke en sti eller sammensat sti +@msg these shapes are too small to measure disse figurer er for små til at blive målt # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentværktøjer Save a Timestamped Copy Gem en kopi med dato og klokkeslæt @@ -9511,7 +9577,7 @@ breakText Glyphs Glyffer @msg stroke cannot be set on a symbol instance stroke kan ikke angives for en symbolforekomst @msg fill on a symbol instance must be a solid color or none fill på en symbolforekomst skal være en ensfarvet farve eller none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan ikke angives for et billede uden effekten Konvertér til form eller Objekt til kontur -@msg pass newName, registration, exportType, nineSlice and/or type angiv newName, registration, exportType, nineSlice og/eller type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid angiv newName, registration, exportType, nineSlice, type og/eller alignToPixelGrid Text Flow Tekstflow By Rows Efter rækker By Columns Efter kolonner diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 58633e2727..0f2c9db947 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1338,6 +1338,8 @@ file-filter Templates Vorlagen Font Family & Style Schriftfamilie und -schnitt Font Family, Style & Size Schriftfamilie, -schnitt und -grad Font List Schriftliste + Show Similar Fonts Ähnliche Schriften anzeigen + Clear Similar Fonts Ähnliche Schriften zurücksetzen Font Preview Size Größe der Schriftvorschau Font Size Schriftgrad Variable Font Variable Schrift @@ -3240,6 +3242,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1} Search commands and tools Befehle und Werkzeuge suchen Search commands and tools… Befehle und Werkzeuge suchen… + Recent Commands Zuletzt verwendete Befehle + No recent commands Keine zuletzt verwendeten Befehle Search Commands… Befehle suchen… Secondary Sekundär Section Symbol Paragrafenzeichen @@ -4388,6 +4392,31 @@ theme Appearance Erscheinungsbild @msg $.evalFile requires a file path $.evalFile erfordert einen Dateipfad @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: Die Zeitüberschreitung muss eine endliche Anzahl von Millisekunden sein, 0 oder mehr @msg $.evalFile: takes a file path and a timeout $.evalFile: nimmt einen Dateipfad und eine Zeitüberschreitung +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} ist nicht definiert +@msg cannot read property '{key}' of {base} die Eigenschaft '{key}' von {base} kann nicht gelesen werden +@msg cannot set property '{key}' of {base} die Eigenschaft '{key}' von {base} kann nicht gesetzt werden +@msg cannot read a property of {base} eine Eigenschaft von {base} kann nicht gelesen werden +@msg cannot set a property of {base} eine Eigenschaft von {base} kann nicht gesetzt werden +@msg cannot define property '{key}': {why} die Eigenschaft '{key}' kann nicht definiert werden: {why} +@msg cannot assign to property '{key}': {why} der Eigenschaft '{key}' kann nichts zugewiesen werden: {why} +@msg cannot delete property '{key}' die Eigenschaft '{key}' kann nicht gelöscht werden +@msg cannot declare function {ident} die Funktion {ident} kann nicht deklariert werden +@msg invalid assignment target ungültiges Zuweisungsziel +@msg the array's length is read-only die Länge des Arrays ist schreibgeschützt +@msg the property cannot be redefined die Eigenschaft kann nicht neu definiert werden +@msg the object is not extensible das Objekt ist nicht erweiterbar +@msg the length cannot be redefined die Länge kann nicht neu definiert werden +@msg it is read-only sie ist schreibgeschützt +@msg an element cannot be deleted ein Element kann nicht gelöscht werden +@msg it has only a getter sie hat nur einen Getter +@msg the value is a primitive der Wert ist ein primitiver Wert @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: Zeile {line}, Spalte {column} in {file}: {e} (ausgelöst) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: Zeile {line}, Spalte {column}: {e} (ausgelöst) @msg {name}: {e} (thrown) {name}: {e} (ausgelöst) @@ -4493,6 +4522,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus @msg Downloaded {what} {what} heruntergeladen @msg Expand Appearance: the selection has a basic appearance Aussehen umwandeln: Die Auswahl hat ein einfaches Aussehen +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all einige Rastereffekte wurden nicht in Bilder umgewandelt: Sie würden mehr als 1.024 Bilder oder insgesamt 256 Megapixel benötigen @msg Expand: no brush strokes selected Umwandeln: keine Pinselkonturen ausgewählt @msg Expand: no gradient fills Umwandeln: keine Verlaufsflächen @msg Expand: nothing to expand Umwandeln: nichts umzuwandeln @@ -5330,6 +5360,10 @@ liquify-list-end {0}, {1} {0} und {1} Cap Height Versalhöhe x-Height x-Höhe ICF Box ICF-Rahmen + Show Sample Muster einblenden + Hide Sample Muster ausblenden + Max Ascent/Descent Max. Höhe/Tiefe + Max Ascender Max. Oberlänge @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` ist der Schrittverweis {r}, den nur `run` und `command_batch` auflösen @msg `ids` must be an array of object ids, not {v} `ids` muss ein Array von Objekt-IDs sein, nicht {v} @msg `colors` must be an array of colors, not {v} `colors` muss ein Array von Farben sein, nicht {v} @@ -5911,7 +5945,7 @@ effect Soft Weich @msg Unknown dimension style Unbekannter Bemaßungsstil @msg Unknown unit Unbekannte Einheit # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Schließt die kreisförmigen Enden offener Profile. Bei einer Teildrehung bleiben die Schnittseiten offen. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Schließt die kreisförmigen Enden offener Profile. Bei einer Teildrehung werden auch die Schnittseiten geschlossen. Distance Abstand @msg span must be "object" or "selection", got {v} span muss "object" oder "selection" sein, nicht {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" platziert einen `gradient`, kein Farbfeld @@ -6064,6 +6098,7 @@ effect Soft Weich Single Word Justification: Ausrichtung einzelner Wörter: Full Justify Blocksatz Minimum must not exceed Desired, nor Desired Maximum. Das Minimum darf den optimalen Wert nicht übersteigen, der optimale Wert nicht das Maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Das Minimum darf den optimalen Wert nicht übersteigen, der optimale Wert nicht das Maximum Minimum Minimum Justification Abstände Add filters from the list above Filter aus der Liste oben hinzufügen @@ -7010,6 +7045,24 @@ breakText Glyphs Glyphen # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Striche in Pfade umwandeln @msg select paths with dashed strokes to expand wählen Sie Pfade mit gestrichelter Kontur zum Umwandeln aus +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Tangentialkreis… + Tangent Circle Tangentialkreis + Circle: Kreis: +@msg `ids` names an object twice `ids` nennt ein Objekt zweimal +@msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus +@msg `radius` must be from 0.01 to 1000000 pt `radius` muss von 0.01 bis 1000000 pt sein +@msg two shapes need a `radius` zwei Formen brauchen einen `radius` +@msg three shapes set the radius themselves: leave `radius` out drei Formen legen den Radius selbst fest: lassen Sie `radius` weg +@msg `circle` must be from 0 to 64 `circle` muss von 0 bis 64 sein +@msg a shape has no outline eine Form hat keinen Umriss +@msg the shapes are too complex: at most 2000 segments in all die Formen sind zu komplex: höchstens 2000 Segmente insgesamt +@msg these shapes take too long to search diese Formen brauchen zu lange für die Suche +@msg more than 64 circles touch these shapes: they may touch along a whole curve mehr als 64 Kreise berühren diese Formen: sie berühren sie womöglich entlang einer ganzen Kurve +@msg no circle touches these shapes kein Kreis berührt diese Formen +@msg `circle` is past the last circle found ({found}) `circle` liegt hinter dem letzten gefundenen Kreis ({found}) +@msg object {value} is not a path or compound path Objekt {value} ist kein Pfad oder zusammengesetzter Pfad +@msg these shapes are too small to measure diese Formen sind zu klein zum Messen # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentwerkzeuge Save a Timestamped Copy Kopie mit Zeitstempel speichern @@ -7064,7 +7117,7 @@ breakText Glyphs Glyphen @msg stroke cannot be set on a symbol instance stroke kann nicht für eine Symbolinstanz gesetzt werden @msg fill on a symbol instance must be a solid color or none fill einer Symbolinstanz muss eine Vollfarbe oder none sein @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kann nicht für ein Bild ohne den Effekt „In Form umwandeln“ oder „Objekt in Pfade umwandeln“ gesetzt werden -@msg pass newName, registration, exportType, nineSlice and/or type geben Sie newName, registration, exportType, nineSlice und/oder type an +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid geben Sie newName, registration, exportType, nineSlice, type und/oder alignToPixelGrid an Text Flow Textfluss By Rows Nach Zeilen By Columns Nach Spalten @@ -8648,7 +8701,9 @@ breakText Glyphs Glyphen @msg position must be normal, superscript or subscript position muss normal, superscript oder subscript sein @msg position must be topLeft, topRight, bottomLeft or bottomRight position muss topLeft, topRight, bottomLeft oder bottomRight sein @msg positions must be between 0 and 100000 pt positions müssen zwischen 0 und 100000 pt liegen +@msg ppi can't be more than {max} for this image ppi darf für dieses Bild nicht mehr als {max} sein @msg ppi must be a positive number, not {ppi} ppi muss eine positive Zahl sein, nicht {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim lässt die Pixel des Bildes unverändert: Lassen Sie ppi weg @msg ppi must be between 1 and 2400 ppi muss zwischen 1 und 2400 liegen @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` ist nicht transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape muss clippingMask|transparency sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3e144df623..332758fe8f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1273,6 +1273,8 @@ font-technology Variable Μεταβλητές Font Family & Style Οικογένεια και στυλ γραμματοσειράς Font Family, Style & Size Οικογένεια, στυλ και μέγεθος γραμματοσειράς Font List Λίστα γραμματοσειρών + Show Similar Fonts Εμφάνιση παρόμοιων γραμματοσειρών + Clear Similar Fonts Απαλοιφή παρόμοιων γραμματοσειρών Font Preview Size Μέγεθος προεπισκόπησης γραμματοσειράς Font Size Μέγεθος γραμματοσειράς Variable Font Μεταβλητή γραμματοσειρά @@ -2462,6 +2464,44 @@ axis Both Και τα δύο @msg $.evalFile requires a file path Το $.evalFile απαιτεί διαδρομή αρχείου @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: το χρονικό όριο πρέπει να είναι πεπερασμένος αριθμός χιλιοστών του δευτερολέπτου, 0 ή περισσότερο @msg $.evalFile: takes a file path and a timeout $.evalFile: δέχεται μια διαδρομή αρχείου και ένα χρονικό όριο +@msg assignment to a constant binding ανάθεση σε σταθερή δέσμευση +@msg invalid array length μη έγκυρο μήκος πίνακα +@msg array literal too long η κυριολεκτική τιμή πίνακα είναι πολύ μεγάλη +@msg the value is not a function η τιμή δεν είναι συνάρτηση +@msg apply was called on a value that is not a function η apply κλήθηκε σε τιμή που δεν είναι συνάρτηση +@msg the argument list is not an object η λίστα ορισμάτων δεν είναι αντικείμενο +@msg too many arguments πάρα πολλά ορίσματα +@msg the value is not a constructor η τιμή δεν είναι κατασκευαστής +@msg cannot convert the object to a primitive value το αντικείμενο δεν μπορεί να μετατραπεί σε πρωτογενή τιμή +@msg cannot convert undefined or null to an object το undefined ή το null δεν μπορεί να μετατραπεί σε αντικείμενο +@msg the right side of 'in' is not an object η δεξιά πλευρά του 'in' δεν είναι αντικείμενο +@msg the right side of 'instanceof' is not a function η δεξιά πλευρά του 'instanceof' δεν είναι συνάρτηση +@msg the function's prototype is not an object το πρωτότυπο της συνάρτησης δεν είναι αντικείμενο +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined το {ident} δεν έχει οριστεί +@msg cannot read property '{key}' of {base} δεν είναι δυνατή η ανάγνωση της ιδιότητας '{key}' του {base} +@msg cannot set property '{key}' of {base} δεν είναι δυνατός ο ορισμός της ιδιότητας '{key}' του {base} +@msg cannot read a property of {base} δεν είναι δυνατή η ανάγνωση ιδιότητας του {base} +@msg cannot set a property of {base} δεν είναι δυνατός ο ορισμός ιδιότητας του {base} +@msg cannot define property '{key}': {why} δεν είναι δυνατός ο καθορισμός της ιδιότητας '{key}': {why} +@msg cannot assign to property '{key}': {why} δεν είναι δυνατή η ανάθεση στην ιδιότητα '{key}': {why} +@msg cannot delete property '{key}' δεν είναι δυνατή η διαγραφή της ιδιότητας '{key}' +@msg cannot declare function {ident} δεν είναι δυνατή η δήλωση της συνάρτησης {ident} +@msg invalid assignment target μη έγκυρος στόχος ανάθεσης +@msg the array's length is read-only το μήκος του πίνακα είναι μόνο για ανάγνωση +@msg the property cannot be redefined η ιδιότητα δεν μπορεί να οριστεί ξανά +@msg the object is not extensible το αντικείμενο δεν είναι επεκτάσιμο +@msg the length cannot be redefined το μήκος δεν μπορεί να οριστεί ξανά +@msg it is read-only είναι μόνο για ανάγνωση +@msg an element cannot be deleted ένα στοιχείο δεν μπορεί να διαγραφεί +@msg it has only a getter έχει μόνο getter +@msg the value is a primitive η τιμή είναι πρωτογενής @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (εξαίρεση) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: γραμμή {line}, στήλη {column}: {e} (εξαίρεση) @msg {name}: {e} (thrown) {name}: {e} (εξαίρεση) @@ -2579,6 +2619,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή @msg Downloaded {what} Έγινε λήψη του {what} @msg Expand Appearance: the selection has a basic appearance Επέκταση εμφάνισης: η επιλογή έχει βασική εμφάνιση +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all ορισμένα εφέ ράστερ δεν μετατράπηκαν σε εικόνες: θα χρειάζονταν περισσότερες από 1.024 εικόνες ή συνολικά 256 megapixel @msg Expand: no brush strokes selected Επέκταση: δεν επιλέχθηκαν πινελιές @msg Expand: no gradient fills Επέκταση: δεν υπάρχουν γεμίσματα ντεγκραντέ @msg Expand: nothing to expand Επέκταση: δεν υπάρχει περιεχόμενο προς επέκταση @@ -3903,6 +3944,8 @@ digits Malayalam Μαλαγιάλαμ Search All Αναζήτηση όλων Search commands and tools Αναζήτηση εντολών και εργαλείων Search commands and tools… Αναζήτηση εντολών και εργαλείων… + Recent Commands Πρόσφατες εντολές + No recent commands Δεν υπάρχουν πρόσφατες εντολές Search Commands… Αναζήτηση εντολών… Secondary Δευτερεύον Section Symbol Σύμβολο ενότητας @@ -5363,6 +5406,10 @@ digits Malayalam Μαλαγιάλαμ Em Box Τετράγωνο em x-Height Ύψος x ICF Box Πλαίσιο ICF + Show Sample Εμφάνιση δείγματος + Hide Sample Απόκρυψη δείγματος + Max Ascent/Descent Μέγ. ύψος/βάθος + Max Ascender Μέγ. άνω επέκταση @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve το `id` είναι η αναφορά βήματος {r}, την οποία αναλύουν μόνο τα `run` και `command_batch` @msg `ids` must be an array of object ids, not {v} το `ids` πρέπει να είναι πίνακας αναγνωριστικών αντικειμένων, όχι {v} @msg `colors` must be an array of colors, not {v} το `colors` πρέπει να είναι πίνακας χρωμάτων, όχι {v} @@ -6195,7 +6242,7 @@ effect Points Σημεία By Object Ανά αντικείμενο Check an artboard to save. Επιλέξτε έναν πίνακα σχεδίασης για αποθήκευση. Clear All Εκκαθάριση όλων - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Κλείσιμο των κυκλικών άκρων των ανοιχτών προφίλ. Οι μερικές περιστροφές κρατούν ανοιχτές τις πλευρές τομής τους. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Κλείσιμο των κυκλικών άκρων των ανοιχτών προφίλ. Οι μερικές περιστροφές κλείνουν επίσης τις πλευρές τομής τους. Color Panel Options Επιλογές πίνακα χρώματος Color blindness – Tritanopia-type Αχρωματοψία – τύπου τριτανοπίας Create Dimension Δημιουργία διάστασης @@ -6449,6 +6496,7 @@ effect Points Σημεία Single Word Justification: Στοίχιση μεμονωμένης λέξης: Full Justify Στοίχιση και στα δύο άκρα Minimum must not exceed Desired, nor Desired Maximum. Το ελάχιστο δεν πρέπει να υπερβαίνει το επιθυμητό, ούτε το επιθυμητό το μέγιστο. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: το ελάχιστο δεν πρέπει να υπερβαίνει το επιθυμητό, ούτε το επιθυμητό το μέγιστο Justification Πλήρης στοίχιση Add filters from the list above Προσθέστε φίλτρα από τη λίστα παραπάνω Add to Stack Προσθήκη στη στοίβα @@ -7388,6 +7436,24 @@ breakText Glyphs Γλύφοι # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Επέκταση παυλών σε διαδρομές @msg select paths with dashed strokes to expand επιλέξτε διαδρομές με διακεκομμένο περίγραμμα για επέκταση +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Εφαπτόμενος κύκλος… + Tangent Circle Εφαπτόμενος κύκλος + Circle: Κύκλος: +@msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές +@msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές +@msg `radius` must be from 0.01 to 1000000 pt το `radius` πρέπει να είναι από 0.01 έως 1000000 pt +@msg two shapes need a `radius` δύο σχήματα χρειάζονται `radius` +@msg three shapes set the radius themselves: leave `radius` out τρία σχήματα ορίζουν μόνα τους την ακτίνα: παραλείψτε το `radius` +@msg `circle` must be from 0 to 64 το `circle` πρέπει να είναι από 0 έως 64 +@msg a shape has no outline ένα σχήμα δεν έχει περίγραμμα +@msg the shapes are too complex: at most 2000 segments in all τα σχήματα είναι υπερβολικά σύνθετα: το πολύ 2000 τμήματα συνολικά +@msg these shapes take too long to search η αναζήτηση για αυτά τα σχήματα διαρκεί υπερβολικά πολύ +@msg more than 64 circles touch these shapes: they may touch along a whole curve περισσότεροι από 64 κύκλοι αγγίζουν αυτά τα σχήματα: ίσως τα αγγίζουν κατά μήκος μιας ολόκληρης καμπύλης +@msg no circle touches these shapes κανένας κύκλος δεν αγγίζει αυτά τα σχήματα +@msg `circle` is past the last circle found ({found}) το `circle` είναι μετά τον τελευταίο κύκλο που βρέθηκε ({found}) +@msg object {value} is not a path or compound path το αντικείμενο {value} δεν είναι διαδρομή ή σύνθετη διαδρομή +@msg these shapes are too small to measure αυτά τα σχήματα είναι πολύ μικρά για να μετρηθούν # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Εργαλεία εγγράφου Save a Timestamped Copy Αποθήκευση αντιγράφου με ημερομηνία και ώρα @@ -7442,7 +7508,7 @@ breakText Glyphs Γλύφοι @msg stroke cannot be set on a symbol instance το stroke δεν μπορεί να οριστεί σε στιγμιότυπο συμβόλου @msg fill on a symbol instance must be a solid color or none το fill ενός στιγμιότυπου συμβόλου πρέπει να είναι συμπαγές χρώμα ή none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it το {key} δεν μπορεί να οριστεί σε εικόνα χωρίς το εφέ «Μετατροπή σε σχήμα» ή «Μετατροπή αντικειμένου σε περιγράμματα» -@msg pass newName, registration, exportType, nineSlice and/or type δώστε newName, registration, exportType, nineSlice ή/και type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid δώστε newName, registration, exportType, nineSlice, type ή/και alignToPixelGrid Text Flow Ροή κειμένου By Rows Κατά γραμμές By Columns Κατά στήλες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2a40b87b60..b12bbde0a3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1036,6 +1036,10 @@ font-technology Variable Variables Em Box Cuadro eme x-Height Altura de la x ICF Box Cuadro ICF + Show Sample Mostrar muestra + Hide Sample Ocultar muestra + Max Ascent/Descent Altura/profundidad máx. + Max Ascender Ascendente máx. Em Dash Raya Em Space Espacio eme Embed Incrustar @@ -1349,6 +1353,8 @@ font-technology Variable Variables Font Family & Style Familia y estilo de fuente Font Family, Style & Size Familia, estilo y tamaño de fuente Font List Lista de fuentes + Show Similar Fonts Mostrar fuentes similares + Clear Similar Fonts Borrar fuentes similares Font Preview Size Tamaño de vista previa de fuente Font Size Tamaño de fuente Variable Font Fuente variable @@ -3274,6 +3280,8 @@ digits Malayalam Malayálam @msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1} Search commands and tools Buscar comandos y herramientas Search commands and tools… Buscar comandos y herramientas… + Recent Commands Comandos recientes + No recent commands No hay comandos recientes Search Commands… Buscar comandos… Secondary Secundario Section Symbol Símbolo de sección @@ -4466,6 +4474,44 @@ axis Both Ambos @msg $.evalFile requires a file path $.evalFile requiere una ruta de archivo @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el tiempo de espera debe ser un número finito de milisegundos, 0 o más @msg $.evalFile: takes a file path and a timeout $.evalFile: recibe una ruta de archivo y un tiempo de espera +@msg assignment to a constant binding asignación a un enlace constante +@msg invalid array length longitud de array no válida +@msg array literal too long el literal de array es demasiado largo +@msg the value is not a function el valor no es una función +@msg apply was called on a value that is not a function se llamó a apply sobre un valor que no es una función +@msg the argument list is not an object la lista de argumentos no es un objeto +@msg too many arguments demasiados argumentos +@msg the value is not a constructor el valor no es un constructor +@msg cannot convert the object to a primitive value no se puede convertir el objeto en un valor primitivo +@msg cannot convert undefined or null to an object no se puede convertir undefined ni null en un objeto +@msg the right side of 'in' is not an object el lado derecho de 'in' no es un objeto +@msg the right side of 'instanceof' is not a function el lado derecho de 'instanceof' no es una función +@msg the function's prototype is not an object el prototipo de la función no es un objeto +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} no está definido +@msg cannot read property '{key}' of {base} no se puede leer la propiedad '{key}' de {base} +@msg cannot set property '{key}' of {base} no se puede establecer la propiedad '{key}' de {base} +@msg cannot read a property of {base} no se puede leer una propiedad de {base} +@msg cannot set a property of {base} no se puede establecer una propiedad de {base} +@msg cannot define property '{key}': {why} no se puede definir la propiedad '{key}': {why} +@msg cannot assign to property '{key}': {why} no se puede asignar a la propiedad '{key}': {why} +@msg cannot delete property '{key}' no se puede eliminar la propiedad '{key}' +@msg cannot declare function {ident} no se puede declarar la función {ident} +@msg invalid assignment target destino de asignación no válido +@msg the array's length is read-only la longitud del array es de solo lectura +@msg the property cannot be redefined la propiedad no se puede redefinir +@msg the object is not extensible el objeto no es extensible +@msg the length cannot be redefined la longitud no se puede redefinir +@msg it is read-only es de solo lectura +@msg an element cannot be deleted no se puede eliminar un elemento +@msg it has only a getter solo tiene un getter +@msg the value is a primitive el valor es primitivo @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línea {line}, columna {column} de {file}: {e} (lanzado) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: línea {line}, columna {column}: {e} (lanzado) @msg {name}: {e} (thrown) {name}: {e} (lanzado) @@ -4582,6 +4628,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado @msg Downloaded {what} Se descargó {what} @msg Expand Appearance: the selection has a basic appearance Expandir apariencia: la selección tiene una apariencia básica +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all algunos efectos ráster no se convirtieron en imágenes: ocuparían más de 1024 imágenes o 256 megapíxeles en total @msg Expand: no brush strokes selected Expandir: no hay trazos de pincel seleccionados @msg Expand: no gradient fills Expandir: no hay rellenos de degradado @msg Expand: nothing to expand Expandir: no hay nada que expandir @@ -6284,7 +6331,7 @@ mark-style Japanese Japonesas @msg Unknown dimension style Estilo de cota desconocido @msg Unknown unit Unidad desconocida # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Cierra los extremos circulares de los perfiles abiertos. Los giros parciales mantienen abiertos sus lados de corte. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Cierra los extremos circulares de los perfiles abiertos. Los giros parciales también cierran sus lados de corte. Distance Distancia @msg span must be "object" or "selection", got {v} span debe ser "object" o "selection", no {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" coloca un `gradient`, no una muestra @@ -6437,6 +6484,7 @@ mark-style Japanese Japonesas Single Word Justification: Justificación de una sola palabra: Full Justify Justificar completamente Minimum must not exceed Desired, nor Desired Maximum. El mínimo no puede superar el deseado, ni el deseado el máximo. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: el mínimo no puede superar el deseado, ni el deseado el máximo Justification Justificación Add filters from the list above Añada filtros de la lista de arriba Add to Stack Añadir a la pila @@ -7376,6 +7424,24 @@ breakText Glyphs Glifos # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir guiones en trazados @msg select paths with dashed strokes to expand seleccione trazados con trazo discontinuo para expandir +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Círculo tangente… + Tangent Circle Círculo tangente + Circle: Círculo: +@msg `ids` names an object twice `ids` indica un objeto dos veces +@msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos +@msg `radius` must be from 0.01 to 1000000 pt `radius` debe ser de 0.01 a 1000000 pt +@msg two shapes need a `radius` dos formas necesitan un `radius` +@msg three shapes set the radius themselves: leave `radius` out tres formas fijan el radio por sí mismas: omita `radius` +@msg `circle` must be from 0 to 64 `circle` debe ser de 0 a 64 +@msg a shape has no outline una forma no tiene contorno +@msg the shapes are too complex: at most 2000 segments in all las formas son demasiado complejas: como máximo 2000 segmentos en total +@msg these shapes take too long to search la búsqueda tarda demasiado con estas formas +@msg more than 64 circles touch these shapes: they may touch along a whole curve más de 64 círculos tocan estas formas: puede que las toquen a lo largo de toda una curva +@msg no circle touches these shapes ningún círculo toca estas formas +@msg `circle` is past the last circle found ({found}) `circle` pasa del último círculo encontrado ({found}) +@msg object {value} is not a path or compound path el objeto {value} no es un trazado ni un trazado compuesto +@msg these shapes are too small to measure estas formas son demasiado pequeñas para medirlas # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Herramientas de documento Save a Timestamped Copy Guardar una copia con fecha y hora @@ -7430,7 +7496,7 @@ breakText Glyphs Glifos @msg stroke cannot be set on a symbol instance stroke no se puede definir en una instancia de símbolo @msg fill on a symbol instance must be a solid color or none el fill de una instancia de símbolo debe ser un color sólido o none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} no se puede definir en una imagen sin el efecto Convertir en forma o Contornear objeto -@msg pass newName, registration, exportType, nineSlice and/or type indique newName, registration, exportType, nineSlice y/o type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indique newName, registration, exportType, nineSlice, type y/o alignToPixelGrid Text Flow Flujo de texto By Rows Por filas By Columns Por columnas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0b575b6975..a2158f4722 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1722,6 +1722,10 @@ digits Malayalam Malajalam Em Box Em-laatikko x-Height x-korkeus ICF Box ICF-laatikko + Show Sample Näytä näyte + Hide Sample Piilota näyte + Max Ascent/Descent Suurin korkeus/syvyys + Max Ascender Suurin yläpidennys Copy Color Value (Hex) Kopioi väriarvo (heksa) Create New Swatch… Luo uusi värimalli… Name 40% Nimi 40% @@ -3635,6 +3639,8 @@ theme Appearance Ulkoasu Find Font Files Etsi fonttitiedostoja Add Font Files Lisää fonttitiedostoja Font List Fonttiluettelo + Show Similar Fonts Näytä samankaltaiset fontit + Clear Similar Fonts Tyhjennä samankaltaiset fontit Fonts in Document Asiakirjan fontit Refresh Font List Päivitä fonttiluettelo Replace Font Korvaa fontti @@ -4394,6 +4400,8 @@ font-technology Variable Muuttuvat Saving Tallennetaan Saving {} Tallennetaan {} Search commands and tools… Hae komentoja ja työkaluja… + Recent Commands Viimeisimmät komennot + No recent commands Ei viimeisimpiä komentoja Dashed Line Katkoviiva Panel menu Paneelivalikko Unembed… Poista upotus… @@ -4699,6 +4707,44 @@ imageTrace Outline Ääriviiva @msg $.evalFile requires a file path $.evalFile vaatii tiedostopolun @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: aikakatkaisun on oltava äärellinen määrä millisekunteja, 0 tai enemmän @msg $.evalFile: takes a file path and a timeout $.evalFile: ottaa tiedostopolun ja aikakatkaisun +@msg assignment to a constant binding sijoitus vakiosidontaan +@msg invalid array length virheellinen taulukon pituus +@msg array literal too long taulukkoliteraali on liian pitkä +@msg the value is not a function arvo ei ole funktio +@msg apply was called on a value that is not a function apply kutsuttiin arvolle, joka ei ole funktio +@msg the argument list is not an object argumenttiluettelo ei ole objekti +@msg too many arguments liikaa argumentteja +@msg the value is not a constructor arvo ei ole konstruktori +@msg cannot convert the object to a primitive value objektia ei voi muuntaa primitiiviarvoksi +@msg cannot convert undefined or null to an object arvoja undefined tai null ei voi muuntaa objektiksi +@msg the right side of 'in' is not an object operaattorin 'in' oikea puoli ei ole objekti +@msg the right side of 'instanceof' is not a function operaattorin 'instanceof' oikea puoli ei ole funktio +@msg the function's prototype is not an object funktion prototyyppi ei ole objekti +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} ei ole määritelty +@msg cannot read property '{key}' of {base} arvon {base} ominaisuutta '{key}' ei voi lukea +@msg cannot set property '{key}' of {base} arvon {base} ominaisuutta '{key}' ei voi asettaa +@msg cannot read a property of {base} arvon {base} ominaisuutta ei voi lukea +@msg cannot set a property of {base} arvon {base} ominaisuutta ei voi asettaa +@msg cannot define property '{key}': {why} ominaisuutta '{key}' ei voi määrittää: {why} +@msg cannot assign to property '{key}': {why} ominaisuuteen '{key}' ei voi sijoittaa: {why} +@msg cannot delete property '{key}' ominaisuutta '{key}' ei voi poistaa +@msg cannot declare function {ident} funktiota {ident} ei voi esitellä +@msg invalid assignment target virheellinen sijoituksen kohde +@msg the array's length is read-only taulukon pituus on vain luku +@msg the property cannot be redefined ominaisuutta ei voi määrittää uudelleen +@msg the object is not extensible objektia ei voi laajentaa +@msg the length cannot be redefined pituutta ei voi määrittää uudelleen +@msg it is read-only se on vain luku +@msg an element cannot be deleted alkiota ei voi poistaa +@msg it has only a getter sillä on vain getter +@msg the value is a primitive arvo on primitiivi @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, rivi {line}, sarake {column}: {e} (heitetty) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: rivi {line}, sarake {column}: {e} (heitetty) @msg {name}: {e} (thrown) {name}: {e} (heitetty) @@ -4815,6 +4861,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku @msg Downloaded {what} Ladattiin {what} @msg Expand Appearance: the selection has a basic appearance Laajenna ulkoasu: valinnalla on perusulkoasu +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all joitakin rasteritehosteita ei muunnettu kuviksi: ne veisivät yli 1 024 kuvaa tai yhteensä 256 megapikseliä @msg Expand: no brush strokes selected Laajenna: sivellinviivoja ei ole valittu @msg Expand: no gradient fills Laajenna: ei liukuväritäyttöjä @msg Expand: nothing to expand Laajenna: ei laajennettavaa @@ -6205,7 +6252,7 @@ mark-style Japanese Japanilainen By Object Objektin mukaan Check an artboard to save. Valitse tallennettava piirtoalusta. Clear All Tyhjennä kaikki - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sulje avointen profiilien pyöreät päät. Osittaiset pyöräytykset jättävät leikkauspintansa auki. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Sulje avointen profiilien pyöreät päät. Osittaiset pyöräytykset sulkevat myös leikkauspintansa. Color Panel Options Väri-paneelin asetukset Color blindness – Tritanopia-type Värisokeus – tritanopia Create Dimension Luo mitta @@ -6459,6 +6506,7 @@ mark-style Japanese Japanilainen Single Word Justification: Yksittäisen sanan tasaus: Full Justify Täysi tasaus Minimum must not exceed Desired, nor Desired Maximum. Minimi ei saa ylittää haluttua arvoa eikä haluttu arvo maksimia. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimi ei saa ylittää haluttua arvoa eikä haluttu arvo maksimia Justification Tasaus Add filters from the list above Lisää suodattimia yllä olevasta luettelosta Add to Stack Lisää pinoon @@ -7464,6 +7512,24 @@ breakText Glyphs Merkit # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Laajenna viivat poluiksi @msg select paths with dashed strokes to expand valitse laajennettavat polut, joissa on katkoviiva +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Sivuava ympyrä… + Tangent Circle Sivuava ympyrä + Circle: Ympyrä: +@msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti +@msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua +@msg `radius` must be from 0.01 to 1000000 pt `radius` on oltava 0.01–1000000 pt +@msg two shapes need a `radius` kaksi muotoa tarvitsee arvon `radius` +@msg three shapes set the radius themselves: leave `radius` out kolme muotoa määrää säteen itse: jätä `radius` pois +@msg `circle` must be from 0 to 64 `circle` on oltava 0–64 +@msg a shape has no outline muodolla ei ole ääriviivaa +@msg the shapes are too complex: at most 2000 segments in all muodot ovat liian monimutkaisia: enintään 2000 segmenttiä yhteensä +@msg these shapes take too long to search haku kestää liian kauan näille muodoille +@msg more than 64 circles touch these shapes: they may touch along a whole curve yli 64 ympyrää sivuaa näitä muotoja: ne saattavat sivuta niitä koko käyrän matkalta +@msg no circle touches these shapes mikään ympyrä ei sivua näitä muotoja +@msg `circle` is past the last circle found ({found}) `circle` on viimeisen löydetyn ympyrän jälkeen ({found}) +@msg object {value} is not a path or compound path objekti {value} ei ole polku eikä yhdistelmäpolku +@msg these shapes are too small to measure nämä muodot ovat liian pieniä mitattaviksi # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Asiakirjatyökalut Save a Timestamped Copy Tallenna kopio aikaleimalla @@ -7518,7 +7584,7 @@ breakText Glyphs Merkit @msg stroke cannot be set on a symbol instance stroke-arvoa ei voi asettaa symbolin ilmentymälle @msg fill on a symbol instance must be a solid color or none symbolin ilmentymän fill-arvon on oltava tasainen väri tai none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key}-arvoa ei voi asettaa kuvalle, jolla ei ole tehostetta Muunna muodoksi tai Muunna objekti ääriviivoiksi -@msg pass newName, registration, exportType, nineSlice and/or type anna newName, registration, exportType, nineSlice ja/tai type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid anna newName, registration, exportType, nineSlice, type ja/tai alignToPixelGrid Text Flow Tekstin kulku By Rows Riveittäin By Columns Sarakkeittain diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1988f6d8d1..70d563f932 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1343,6 +1343,8 @@ font-technology Variable Variables Font Family & Style Famille et style de police Font Family, Style & Size Famille, style et taille de police Font List Liste des polices + Show Similar Fonts Afficher les polices similaires + Clear Similar Fonts Effacer les polices similaires Font Preview Size Taille de l’aperçu des polices Font Size Taille de police Variable Font Police variable @@ -3266,6 +3268,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1} Search commands and tools Chercher commandes et outils Search commands and tools… Chercher commandes et outils… + Recent Commands Commandes récentes + No recent commands Aucune commande récente Search Commands… Rechercher des commandes… Secondary Secondaire Section Symbol Symbole de section @@ -4455,6 +4459,31 @@ axis Both Les deux @msg $.evalFile requires a file path $.evalFile nécessite un chemin de fichier @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile : le délai doit être un nombre fini de millisecondes, 0 ou plus @msg $.evalFile: takes a file path and a timeout $.evalFile : prend un chemin de fichier et un délai +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} n'est pas défini +@msg cannot read property '{key}' of {base} impossible de lire la propriété '{key}' de {base} +@msg cannot set property '{key}' of {base} impossible de modifier la propriété '{key}' de {base} +@msg cannot read a property of {base} impossible de lire une propriété de {base} +@msg cannot set a property of {base} impossible de modifier une propriété de {base} +@msg cannot define property '{key}': {why} impossible de définir la propriété '{key}' : {why} +@msg cannot assign to property '{key}': {why} impossible d'affecter la propriété '{key}' : {why} +@msg cannot delete property '{key}' impossible de supprimer la propriété '{key}' +@msg cannot declare function {ident} impossible de déclarer la fonction {ident} +@msg invalid assignment target cible d'affectation non valide +@msg the array's length is read-only la longueur du tableau est en lecture seule +@msg the property cannot be redefined la propriété ne peut pas être redéfinie +@msg the object is not extensible l'objet n'est pas extensible +@msg the length cannot be redefined la longueur ne peut pas être redéfinie +@msg it is read-only elle est en lecture seule +@msg an element cannot be deleted un élément ne peut pas être supprimé +@msg it has only a getter elle n'a qu'un getter +@msg the value is a primitive la valeur est une primitive @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name} : ligne {line}, colonne {column} de {file} : {e} (levée) @msg {name}: line {line}, column {column}: {e} (thrown) {name} : ligne {line}, colonne {column} : {e} (levée) @msg {name}: {e} (thrown) {name} : {e} (levée) @@ -4560,6 +4589,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg select a path sélectionnez un tracé @msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé @msg Downloaded {what} {what} téléchargé +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all certains effets pixellisés n’ont pas été convertis en images, car ils occuperaient plus de 1024 images ou 256 mégapixels au total @msg Expand Appearance: the selection has a basic appearance Décomposer l’aspect : la sélection a un aspect de base @msg Expand: no brush strokes selected Décomposer : aucun contour de forme sélectionné @msg Expand: no gradient fills Décomposer : aucun fond en dégradé @@ -5393,6 +5423,10 @@ liquify-list-end {0}, {1} {0} et {1} Em Box Cadratin x-Height Hauteur d’x ICF Box Cadre ICF + Show Sample Afficher l'échantillon + Hide Sample Masquer l'échantillon + Max Ascent/Descent Hauteur/profondeur max. + Max Ascender Jambage ascendant max. ICF Top/Right ICF haut/droite ICF Bottom/Left ICF bas/gauche @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` est la référence d’étape {r}, que seuls `run` et `command_batch` résolvent @@ -6325,7 +6359,7 @@ theme Appearance Apparence @msg Unknown dimension style Style de cote inconnu @msg Unknown unit Unité inconnue # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Ferme les extrémités circulaires des profils ouverts. Les rotations partielles conservent leurs faces de coupe ouvertes. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Ferme les extrémités circulaires des profils ouverts. Les rotations partielles ferment aussi leurs faces de coupe. @msg span must be "object" or "selection", got {v} span doit être "object" ou "selection", pas {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" place un `gradient`, pas une nuance @msg span: "selection" places a gradient: give `gradient` span: "selection" place un dégradé : indiquez `gradient` @@ -6477,6 +6511,7 @@ theme Appearance Apparence Single Word Justification: Justification d’un mot isolé : Full Justify Justification complète Minimum must not exceed Desired, nor Desired Maximum. Le minimum ne doit pas dépasser la valeur optimale, ni la valeur optimale le maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}` : le minimum ne doit pas dépasser la valeur optimale, ni la valeur optimale le maximum Justification Justification Add filters from the list above Ajoutez des filtres à partir de la liste ci-dessus Add to Stack Ajouter à la pile @@ -7414,6 +7449,24 @@ breakText Glyphs Glyphes # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Cercle tangent… + Tangent Circle Cercle tangent + Circle: Cercle : +@msg `ids` names an object twice `ids` désigne deux fois le même objet +@msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents +@msg `radius` must be from 0.01 to 1000000 pt `radius` doit être compris entre 0.01 et 1000000 pt +@msg two shapes need a `radius` deux formes demandent un `radius` +@msg three shapes set the radius themselves: leave `radius` out trois formes fixent elles-mêmes le rayon : omettez `radius` +@msg `circle` must be from 0 to 64 `circle` doit être compris entre 0 et 64 +@msg a shape has no outline une forme n’a pas de contour +@msg the shapes are too complex: at most 2000 segments in all les formes sont trop complexes : 2000 segments au plus au total +@msg these shapes take too long to search la recherche prend trop de temps pour ces formes +@msg more than 64 circles touch these shapes: they may touch along a whole curve plus de 64 cercles touchent ces formes : ils les touchent peut-être le long d’une courbe entière +@msg no circle touches these shapes aucun cercle ne touche ces formes +@msg `circle` is past the last circle found ({found}) `circle` dépasse le dernier cercle trouvé ({found}) +@msg object {value} is not a path or compound path l’objet {value} n’est ni un tracé ni un tracé transparent +@msg these shapes are too small to measure ces formes sont trop petites pour être mesurées # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Outils de document Save a Timestamped Copy Enregistrer une copie horodatée @@ -7468,7 +7521,7 @@ breakText Glyphs Glyphes @msg stroke cannot be set on a symbol instance stroke ne peut pas être défini sur une instance de symbole @msg fill on a symbol instance must be a solid color or none le fill d’une instance de symbole doit être une couleur unie ou none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} ne peut pas être défini sur une image sans l’effet Convertir en forme ou Vectoriser l’objet -@msg pass newName, registration, exportType, nineSlice and/or type indiquez newName, registration, exportType, nineSlice et/ou type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid indiquez newName, registration, exportType, nineSlice, type et/ou alignToPixelGrid Text Flow Flux du texte By Rows Par lignes By Columns Par colonnes @@ -8929,7 +8982,9 @@ breakText Glyphs Glyphes @msg position must be normal, superscript or subscript position doit valoir normal, superscript ou subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position doit valoir topLeft, topRight, bottomLeft ou bottomRight @msg positions must be between 0 and 100000 pt les positions doivent être comprises entre 0 et 100000 pt +@msg ppi can't be more than {max} for this image ppi ne peut pas dépasser {max} pour cette image @msg ppi must be a positive number, not {ppi} ppi doit être un nombre positif, pas {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim conserve les pixels de l’image tels quels : omettez ppi @msg ppi must be between 1 and 2400 ppi doit être compris entre 1 et 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` n’est pas transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape doit valoir clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index dd903bc267..0e29714102 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -556,6 +556,7 @@ Chosen: {n} of {total} પસંદ કરેલ: {total} માંથી {n} Chrome… ક્રોમ… Circle વર્તુળ + Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો Clean Up… સાફ કરો… @@ -607,7 +608,7 @@ Close Path… પાથ બંધ કરો… Close or Join બંધ કરો અથવા જોડો Close paths when ends are within: છેડા આ અંતરમાં હોય ત્યારે પાથ બંધ કરો: - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ખુલ્લી પ્રોફાઇલના ગોળ છેડા બંધ કરો. આંશિક સ્વીપ તેમની કાપેલી બાજુઓ ખુલ્લી રાખે છે. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. ખુલ્લી પ્રોફાઇલના ગોળ છેડા બંધ કરો. આંશિક સ્વીપ તેમની કાપેલી બાજુઓ પણ બંધ કરે છે. Closing bracket with no opening one ખુલતા કૌંસ વગરનો બંધ થતો કૌંસ Coincidence: સંયોગ: Collapse Panel Group પેનલ ગ્રૂપ સંકોચો @@ -1457,6 +1458,8 @@ Font Family, Style & Size ફોન્ટ ફેમિલી, સ્ટાઇલ અને સાઇઝ Font Family: ફોન્ટ ફેમિલી: Font List ફોન્ટ યાદી + Show Similar Fonts સમાન ફોન્ટ બતાવો + Clear Similar Fonts સમાન ફોન્ટ સાફ કરો Font Preview Size ફોન્ટ પૂર્વાવલોકન સાઇઝ Font Size ફોન્ટ સાઇઝ Font Style: ફોન્ટ સ્ટાઇલ: @@ -1738,6 +1741,10 @@ ICC Profile ICC પ્રોફાઇલ ICF Bottom/Left ICF નીચે/ડાબે ICF Box ICF બૉક્સ + Show Sample નમૂનો બતાવો + Hide Sample નમૂનો છુપાવો + Max Ascent/Descent મહત્તમ એસેન્ટ/ડિસેન્ટ + Max Ascender મહત્તમ એસેન્ડર ICF Top/Right ICF ઉપર/જમણે ID: {id} ID: {id} Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો @@ -3364,6 +3371,8 @@ Search Preferences પસંદગીઓ શોધો Search commands and tools આદેશો અને ટૂલ્સ શોધો Search commands and tools… આદેશો અને ટૂલ્સ શોધો… + Recent Commands તાજેતરના આદેશો + No recent commands કોઈ તાજેતરના આદેશો નથી Search images છબીઓ શોધો Searching… શોધી રહ્યા છીએ… Secondary ગૌણ @@ -3856,6 +3865,8 @@ Table ટેબલ Tabs ટૅબ Tamil તમિલ + Tangent Circle સ્પર્શક વર્તુળ + Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય Target Contents લક્ષ્ય સામગ્રી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 325e6809c7..cbabdbfa1d 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -821,6 +821,7 @@ antiAlias Sharp शार्प Chrome… क्रोम… Circle वृत्त Circle (open) सर्किल (ओपन) + Circle: वृत्त: Classic क्लासिक Classic Defaults क्लासिक डिफ़ॉल्ट Clean Up क्लीन अप @@ -880,7 +881,7 @@ antiAlias Sharp शार्प Close Path: बंद पाथ: Close Path… बंद पाथ… Close paths when ends are within: जब समाप्त होता है तो बंद पाथ भीतर होते हैं: - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड खुली रहती हैं। + Close the circular ends of open profiles. Partial sweeps also close their cut sides. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड भी बंद होती हैं। Closed बंद Closing bracket with no opening one बंद करने वाला ब्रैकेट, जिसका कोई खोलने वाला ब्रैकेट नहीं है Clumped गुच्छेदार @@ -2004,6 +2005,8 @@ antiAlias Sharp शार्प Font Family, Style & Size फ़ॉन्ट परिवार, स्टाइल और आकार Font Family: फ़ॉन्ट परिवार: Font List फ़ॉन्ट सूची + Show Similar Fonts समान फ़ॉन्ट दिखाएँ + Clear Similar Fonts समान फ़ॉन्ट साफ़ करें Font Preview Size फ़ॉन्ट प्रीव्यू साइज़ Font Size फ़ॉन्ट साइज़ Font Size: फ़ॉन्ट साइज़: @@ -2374,6 +2377,10 @@ antiAlias Sharp शार्प ICC Profile ICC प्रोफ़ाइल ICF Bottom/Left ICF बॉटम/लेफ्ट ICF Box ICF बॉक्स + Show Sample नमूना दिखाएँ + Hide Sample नमूना छिपाएँ + Max Ascent/Descent अधिकतम एसेंट/डिसेंट + Max Ascender अधिकतम एसेंडर ICF Top/Right ICF ऊपर/दाएँ Identify Objects By ऑब्जेक्ट्स की पहचान करके If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. अगर ड्रॉइंग टैबलेट के पेन से ड्रॉ नहीं हो रहा, तो X11 (XWayland) ऑप्शन चुनें। @@ -4454,6 +4461,8 @@ antiAlias Sharp शार्प Search artboards खोज आर्टबोर्ड Search commands and tools खोज आदेश और टूल Search commands and tools… आदेश और टूल खोजें… + Recent Commands हाल के आदेश + No recent commands कोई हाल का आदेश नहीं Search Commands… कमांड खोजें… Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर Search images इमेज खोजना @@ -5142,6 +5151,8 @@ antiAlias Sharp शार्प Tag (open) टैग (ओपन) Tail: पूंछ: Tamil तमिल + Tangent Circle स्पर्शी वृत्त + Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य Target Contents लक्ष्य सामग्री @@ -6810,6 +6821,44 @@ antiAlias Sharp शार्प @msg $.evalFile requires a file path $.evalFile के लिए फ़ाइल पाथ आवश्यक है @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: टाइमआउट मिलीसेकंड की एक सीमित संख्या होनी चाहिए, 0 या अधिक @msg $.evalFile: takes a file path and a timeout $.evalFile: एक फ़ाइल पाथ और एक टाइमआउट लेता है +@msg assignment to a constant binding स्थिर बाइंडिंग को मान दिया गया +@msg invalid array length ऐरे की लंबाई अमान्य है +@msg array literal too long ऐरे लिटरल बहुत लंबा है +@msg the value is not a function मान कोई फ़ंक्शन नहीं है +@msg apply was called on a value that is not a function apply को ऐसे मान पर कॉल किया गया जो फ़ंक्शन नहीं है +@msg the argument list is not an object आर्गुमेंट सूची कोई ऑब्जेक्ट नहीं है +@msg too many arguments बहुत अधिक आर्गुमेंट +@msg the value is not a constructor मान कोई कंस्ट्रक्टर नहीं है +@msg cannot convert the object to a primitive value ऑब्जेक्ट को प्रिमिटिव मान में नहीं बदला जा सकता +@msg cannot convert undefined or null to an object undefined या null को ऑब्जेक्ट में नहीं बदला जा सकता +@msg the right side of 'in' is not an object 'in' का दायाँ पक्ष कोई ऑब्जेक्ट नहीं है +@msg the right side of 'instanceof' is not a function 'instanceof' का दायाँ पक्ष कोई फ़ंक्शन नहीं है +@msg the function's prototype is not an object फ़ंक्शन का प्रोटोटाइप कोई ऑब्जेक्ट नहीं है +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} परिभाषित नहीं है +@msg cannot read property '{key}' of {base} {base} की प्रॉपर्टी '{key}' पढ़ी नहीं जा सकती +@msg cannot set property '{key}' of {base} {base} की प्रॉपर्टी '{key}' सेट नहीं की जा सकती +@msg cannot read a property of {base} {base} की कोई प्रॉपर्टी पढ़ी नहीं जा सकती +@msg cannot set a property of {base} {base} की कोई प्रॉपर्टी सेट नहीं की जा सकती +@msg cannot define property '{key}': {why} प्रॉपर्टी '{key}' परिभाषित नहीं की जा सकती: {why} +@msg cannot assign to property '{key}': {why} प्रॉपर्टी '{key}' को मान नहीं दिया जा सकता: {why} +@msg cannot delete property '{key}' प्रॉपर्टी '{key}' हटाई नहीं जा सकती +@msg cannot declare function {ident} फ़ंक्शन {ident} घोषित नहीं किया जा सकता +@msg invalid assignment target मान देने का लक्ष्य अमान्य है +@msg the array's length is read-only ऐरे की लंबाई केवल-पठन है +@msg the property cannot be redefined प्रॉपर्टी को फिर से परिभाषित नहीं किया जा सकता +@msg the object is not extensible ऑब्जेक्ट विस्तार योग्य नहीं है +@msg the length cannot be redefined लंबाई को फिर से परिभाषित नहीं किया जा सकता +@msg it is read-only यह केवल-पठन है +@msg an element cannot be deleted कोई तत्व हटाया नहीं जा सकता +@msg it has only a getter इसमें केवल getter है +@msg the value is a primitive मान प्रिमिटिव है @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (थ्रो किया गया) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: लाइन {line}, कॉलम {column}: {e} (थ्रो किया गया) @msg {name}: {e} (thrown) {name}: {e} (थ्रो किया गया) @@ -7021,6 +7070,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg every search thread stopped on an internal error (please report this bug) प्रत्येक खोज धागा एक आंतरिक त्रुटि पर बंद कर दिया (कृपया इस बग की रिपोर्ट करें) @msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें @msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all कुछ रास्टर इफ़ेक्ट इमेज में नहीं बदले गए: उनके लिए 1,024 से अधिक इमेज या कुल 256 मेगापिक्सेल लगते @msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं @msg Expand: no gradient fills एक्सपैंड: कोई ग्रेडिएंट फ़िल नहीं @msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं @@ -7868,7 +7918,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg parameters must be an object parameters एक ऑब्जेक्ट होना चाहिए @msg params must be an object params एक ऑब्जेक्ट होना चाहिए @msg part of the program isn't valid PostScript text कार्यक्रम का हिस्सा मान्य नहीं है PostScript टेक्स्ट -@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice और/या type दें +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type और/या alignToPixelGrid दें @msg passwords can have up to {MAX_PASSWORD} bytes पासवर्ड {MAX_PASSWORD} बाइट्स तक हो सकता है @msg paste unavailable पेस्ट करें अनुपलब्ध @msg Pasting चिपकाना @@ -7921,7 +7971,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg position must be normal, superscript or subscript position normal, superscript या subscript होना चाहिए @msg position must be topLeft, topRight, bottomLeft or bottomRight position को topLeft, topRight, bottomLeft या bottomRight होना चाहिए @msg positions must be between 0 and 100000 pt positions 0 और 100000 pt के बीच होनी चाहिए +@msg ppi can't be more than {max} for this image इस छवि के लिए ppi {max} से अधिक नहीं हो सकता @msg ppi must be a positive number, not {ppi} ppi एक धनात्मक संख्या होनी चाहिए, {ppi} नहीं +@msg trim keeps the image's pixels as they are: leave out ppi trim छवि के पिक्सेल जैसे हैं वैसे ही रखता है: ppi न दें @msg ppi must be between 1 and 2400 ppi 1 और 2400 के बीच होना चाहिए @msg precision must be from 0.001 to 10 pt precision 0.001 से 10 pt तक होनी चाहिए @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill में से नहीं है @@ -8090,6 +8142,20 @@ liquify-list-end {0}, {1} {0} और {1} @msg select paths, or segments, to divide विभाजित करने के लिए पाथ, या खंड चुनें @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें +@msg select two or three paths or compound paths दो या तीन पाथ या यौगिक पाथ सिलेक्ट करें +@msg `ids` names an object twice `ids` एक ऑब्जेक्ट को दो बार बताता है +@msg `radius` must be from 0.01 to 1000000 pt `radius` 0.01 से 1000000 pt तक होना चाहिए +@msg two shapes need a `radius` दो आकृतियों के लिए `radius` चाहिए +@msg three shapes set the radius themselves: leave `radius` out तीन आकृतियाँ त्रिज्या खुद तय करती हैं: `radius` न दें +@msg `circle` must be from 0 to 64 `circle` 0 से 64 तक होना चाहिए +@msg a shape has no outline एक आकृति की कोई आउटलाइन नहीं है +@msg the shapes are too complex: at most 2000 segments in all आकृतियाँ बहुत जटिल हैं: कुल मिलाकर अधिकतम 2000 सेगमेंट +@msg these shapes take too long to search इन आकृतियों की खोज में बहुत ज़्यादा समय लगता है +@msg more than 64 circles touch these shapes: they may touch along a whole curve इन आकृतियों को 64 से ज़्यादा वृत्त छूते हैं: शायद वे पूरे वक्र के साथ छूते हैं +@msg no circle touches these shapes कोई भी वृत्त इन आकृतियों को नहीं छूता +@msg `circle` is past the last circle found ({found}) `circle` मिले हुए आखिरी वृत्त से आगे है ({found}) +@msg object {value} is not a path or compound path ऑब्जेक्ट {value} पाथ या यौगिक पाथ नहीं है +@msg these shapes are too small to measure ये आकृतियाँ मापने के लिए बहुत छोटी हैं @msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें @msg select segments, or paths, to add points to पॉइंट्स जोड़ने के लिए सेगमेंट या पाथ सिलेक्ट करें @msg select some type first पहले कुछ टाइप सिलेक्ट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3d0ffb11e1..019ba2b72a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1678,6 +1678,8 @@ file-filter Templates Sablonok Font Family & Style Betűcsalád és stílus Font Family, Style & Size Betűcsalád, stílus és méret Font List Betűtípuslista + Show Similar Fonts Hasonló betűtípusok megjelenítése + Clear Similar Fonts Hasonló betűtípusok törlése Font Preview Size Betűtípus-előnézet mérete Font Size Betűméret Variable Font Változó betűtípus @@ -2155,6 +2157,10 @@ file-filter Templates Sablonok Em Box Kvirtmező x-Height x-magasság ICF Box ICF-mező + Show Sample Minta megjelenítése + Hide Sample Minta elrejtése + Max Ascent/Descent Max. magasság/mélység + Max Ascender Max. felnyúló szár ICF Top/Right ICF teteje/jobb oldala Identify Objects By Objektumok azonosítása Ignore Kihagy @@ -3894,6 +3900,8 @@ mark-style Japanese Japán @msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1} Search commands and tools Parancsok és eszközök keresése Search commands and tools… Parancsok és eszközök keresése… + Recent Commands Legutóbbi parancsok + No recent commands Nincsenek legutóbbi parancsok Search Commands… Parancsok keresése… Search Fonts Folder Keresés betűtípusmappában Searching… Keresés… @@ -5287,6 +5295,31 @@ imageTrace Outline Körvonal @msg $.evalFile requires a file path A $.evalFile fájlútvonalat igényel @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: az időkorlátnak véges számú ezredmásodpercnek kell lennie, 0 vagy több @msg $.evalFile: takes a file path and a timeout $.evalFile: egy fájlútvonalat és egy időkorlátot vár +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} nincs definiálva +@msg cannot read property '{key}' of {base} a(z) {base} '{key}' tulajdonsága nem olvasható +@msg cannot set property '{key}' of {base} a(z) {base} '{key}' tulajdonsága nem állítható be +@msg cannot read a property of {base} a(z) {base} tulajdonsága nem olvasható +@msg cannot set a property of {base} a(z) {base} tulajdonsága nem állítható be +@msg cannot define property '{key}': {why} a(z) '{key}' tulajdonság nem definiálható: {why} +@msg cannot assign to property '{key}': {why} a(z) '{key}' tulajdonságnak nem adható érték: {why} +@msg cannot delete property '{key}' a(z) '{key}' tulajdonság nem törölhető +@msg cannot declare function {ident} a(z) {ident} függvény nem deklarálható +@msg invalid assignment target érvénytelen értékadási cél +@msg the array's length is read-only a tömb hossza csak olvasható +@msg the property cannot be redefined a tulajdonság nem definiálható újra +@msg the object is not extensible az objektum nem bővíthető +@msg the length cannot be redefined a hossz nem definiálható újra +@msg it is read-only csak olvasható +@msg an element cannot be deleted elem nem törölhető +@msg it has only a getter csak gettere van +@msg the value is a primitive az érték primitív @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, {line}. sor, {column}. oszlop: {e} (kivétel) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line}. sor, {column}. oszlop: {e} (kivétel) @msg {name}: {e} (thrown) {name}: {e} (kivétel) @@ -5413,6 +5446,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it egy diagram adatsorában a diagramminta grafikája a mintából rajzolódik újra: a módosításához szerkeszd a mintát @msg every search thread stopped on an internal error (please report this bug) minden keresési szál belső hibával leállt (kérjük, jelentsd ezt a hibát) @msg Expand Appearance: the selection has a basic appearance Megjelenés kibontása: a kijelölésnek alapmegjelenése van +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all néhány raszteres effektus nem lett képpé alakítva: több mint 1024 képet vagy összesen 256 megapixelt foglalnának @msg Expand: no brush strokes selected Kibontás: nincs kijelölt ecsetvonás @msg Expand: no gradient fills Kibontás: nincs színátmenetes kitöltés @msg Expand: nothing to expand Kibontás: nincs mit kibontani @@ -6313,7 +6347,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg Unknown dimension style Ismeretlen méretezési stílus @msg Unknown unit Ismeretlen mértékegység # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Nyitott profilok kör alakú végeinek lezárása. Részleges körforgatás esetén a vágott oldalak nyitva maradnak. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Nyitott profilok kör alakú végeinek lezárása. Részleges körforgatás esetén a vágott oldalak is lezáródnak. Distance Távolság @msg span must be "object" or "selection", got {v} a span értéke "object" vagy "selection" lehet, nem {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" egy `gradient` értéket helyez el, nem színmintát @@ -6466,6 +6500,7 @@ liquify-list-end {0}, {1} {0} és {1} Single Word Justification: Egyetlen szó igazítása: Full Justify Teljes sorkizárás Minimum must not exceed Desired, nor Desired Maximum. A minimum nem haladhatja meg a kívánt értéket, sem a kívánt érték a maximumot. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: a minimum nem haladhatja meg a kívánt értéket, sem a kívánt érték a maximumot Justification Sorkizárás Add filters from the list above Adjon hozzá szűrőket a fenti listából Add to Stack Hozzáadás a veremhez @@ -7404,6 +7439,24 @@ breakText Glyphs Glifák # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Szaggatások kibontása útvonalakká @msg select paths with dashed strokes to expand jelöljön ki szaggatott körvonalú útvonalakat a kibontáshoz +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Érintőkör… + Tangent Circle Érintőkör + Circle: Kör: +@msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg +@msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat +@msg `radius` must be from 0.01 to 1000000 pt a `radius` értéke 0.01 és 1000000 pt között lehet +@msg two shapes need a `radius` két alakzathoz `radius` kell +@msg three shapes set the radius themselves: leave `radius` out három alakzat maga határozza meg a sugarat: hagyd el a `radius` értéket +@msg `circle` must be from 0 to 64 a `circle` értéke 0 és 64 között lehet +@msg a shape has no outline egy alakzatnak nincs körvonala +@msg the shapes are too complex: at most 2000 segments in all az alakzatok túl összetettek: összesen legfeljebb 2000 szakasz +@msg these shapes take too long to search ezeknek az alakzatoknak a keresése túl sokáig tart +@msg more than 64 circles touch these shapes: they may touch along a whole curve több mint 64 kör érinti ezeket az alakzatokat: lehet, hogy egy teljes görbe mentén érintik őket +@msg no circle touches these shapes egyetlen kör sem érinti ezeket az alakzatokat +@msg `circle` is past the last circle found ({found}) a `circle` az utolsó talált kör után van ({found}) +@msg object {value} is not a path or compound path a(z) {value} objektum nem útvonal és nem összetett útvonal +@msg these shapes are too small to measure ezek az alakzatok túl kicsik a méréshez # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentumeszközök Save a Timestamped Copy Másolat mentése időbélyeggel @@ -7458,7 +7511,7 @@ breakText Glyphs Glifák @msg stroke cannot be set on a symbol instance a stroke nem állítható be szimbólumpéldányon @msg fill on a symbol instance must be a solid color or none a szimbólumpéldány fill értéke csak egyszínű szín vagy none lehet @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it a {key} nem állítható be olyan képen, amelyen nincs Átalakítás alakzattá vagy Objektum útvonallá alakítása effektus -@msg pass newName, registration, exportType, nineSlice and/or type adja meg a newName, registration, exportType, nineSlice és/vagy type értékét +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid adja meg a newName, registration, exportType, nineSlice, type és/vagy alignToPixelGrid értékét Text Flow Szövegfolyás By Rows Soronként By Columns Oszloponként @@ -8939,7 +8992,9 @@ breakText Glyphs Glifák @msg position must be normal, superscript or subscript position: normal, superscript vagy subscript kell @msg position must be topLeft, topRight, bottomLeft or bottomRight position: topLeft, topRight, bottomLeft vagy bottomRight kell @msg positions must be between 0 and 100000 pt positions: 0 és 100000 pt közötti értékek kellenek +@msg ppi can't be more than {max} for this image ppi: ennél a képnél legfeljebb {max} lehet @msg ppi must be a positive number, not {ppi} ppi: pozitív szám kell, ez nem az: {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi a trim változatlanul hagyja a kép képpontjait: hagyja el a ppi értéket @msg ppi must be between 1 and 2400 ppi: 1 és 2400 közötti érték kell @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`: nem transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape: clippingMask|transparency kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 760f0b591a..b4d8beb213 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1605,6 +1605,10 @@ digits Malayalam Malayalam Em Box Em Box x-Height Tinggi x ICF Box Kotak ICF + Show Sample Tampilkan contoh + Hide Sample Sembunyikan contoh + Max Ascent/Descent Tinggi/kedalaman maks. + Max Ascender Ascender maks. Copy Color Value (Hex) Salin nilai warna (Hex) Create New Swatch… Buat swatch baru… Name 40% Nama 40% @@ -3371,6 +3375,8 @@ theme Appearance Tampilan Find Font Files Cari file font Add Font Files Tambahkan file font Font List Daftar font + Show Similar Fonts Tampilkan font serupa + Clear Similar Fonts Hapus font serupa Fonts in Document Font dalam dokumen Refresh Font List Segarkan daftar font Replace Font Ganti font @@ -4126,6 +4132,8 @@ font-technology Variable Variabel Saving Menyimpan Saving {} Menyimpan {} Search commands and tools… Cari perintah dan alat… + Recent Commands Perintah terbaru + No recent commands Tidak ada perintah terbaru Dashed Line Garis putus-putus Panel menu Menu panel Unembed… Lepaskan sematan… @@ -5655,7 +5663,7 @@ mark-style Japanese Jepang @msg Unknown dimension orientation Orientasi dimensi tidak dikenal @msg Unknown dimension style Gaya dimensi tidak dikenal @msg Unknown unit Satuan tidak dikenal - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Menutup ujung melingkar profil terbuka. Sapuan parsial mempertahankan sisi potongannya tetap terbuka. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Menutup ujung melingkar profil terbuka. Sapuan parsial juga menutup sisi potongannya. Darkness Kegelapan Isolate Selected Object Isolasikan objek terpilih Keep selected Tetap terseleksi @@ -6766,6 +6774,24 @@ breakText Glyphs Glif # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Perluas garis putus menjadi jalur @msg select paths with dashed strokes to expand pilih jalur dengan stroke putus-putus yang akan diperluas +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Lingkaran singgung… + Tangent Circle Lingkaran singgung + Circle: Lingkaran: +@msg `ids` names an object twice `ids` menyebut satu objek dua kali +@msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan +@msg `radius` must be from 0.01 to 1000000 pt `radius` harus dari 0.01 sampai 1000000 pt +@msg two shapes need a `radius` dua bentuk memerlukan `radius` +@msg three shapes set the radius themselves: leave `radius` out tiga bentuk menentukan jari-jarinya sendiri: hilangkan `radius` +@msg `circle` must be from 0 to 64 `circle` harus dari 0 sampai 64 +@msg a shape has no outline sebuah bentuk tidak punya garis luar +@msg the shapes are too complex: at most 2000 segments in all bentuknya terlalu rumit: paling banyak 2000 segmen seluruhnya +@msg these shapes take too long to search pencarian untuk bentuk ini memakan waktu terlalu lama +@msg more than 64 circles touch these shapes: they may touch along a whole curve lebih dari 64 lingkaran menyentuh bentuk ini: mungkin menyentuhnya di sepanjang satu kurva utuh +@msg no circle touches these shapes tidak ada lingkaran yang menyentuh bentuk ini +@msg `circle` is past the last circle found ({found}) `circle` melewati lingkaran terakhir yang ditemukan ({found}) +@msg object {value} is not a path or compound path objek {value} bukan jalur atau jalur gabungan +@msg these shapes are too small to measure bentuk ini terlalu kecil untuk diukur # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Alat dokumen Save a Timestamped Copy Simpan salinan bercap waktu @@ -6820,7 +6846,7 @@ breakText Glyphs Glif @msg stroke cannot be set on a symbol instance stroke tidak dapat diatur pada instans simbol @msg fill on a symbol instance must be a solid color or none fill pada instans simbol harus berupa warna solid atau none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} tidak dapat diatur pada gambar tanpa efek Konversi ke bentuk atau Kerangka objek -@msg pass newName, registration, exportType, nineSlice and/or type berikan newName, registration, exportType, nineSlice dan/atau type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid berikan newName, registration, exportType, nineSlice, type dan/atau alignToPixelGrid Text Flow Alur teks By Rows Per baris By Columns Per kolom diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a46a0f14b6..1ed9c775a7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1045,6 +1045,10 @@ font-technology Variable Variabili Cap Height Altezza maiuscole x-Height Altezza x ICF Box Riquadro ICF + Show Sample Mostra campione + Hide Sample Nascondi campione + Max Ascent/Descent Altezza/profondità max + Max Ascender Ascendente max Em Dash Lineetta Em Space Spazio em Embed Incorpora @@ -1368,6 +1372,8 @@ file-filter Templates Modelli Font Family & Style Famiglia e stile font Font Family, Style & Size Famiglia, stile e dimensione font Font List Elenco font + Show Similar Fonts Mostra font simili + Clear Similar Fonts Cancella font simili Font Preview Size Dimensione anteprima font Font Size Dimensione font Variable Font Font variabile @@ -3317,6 +3323,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1} Search commands and tools Cerca comandi e strumenti Search commands and tools… Cerca comandi e strumenti… + Recent Commands Comandi recenti + No recent commands Nessun comando recente Search Commands… Cerca comandi… Secondary Secondario Section Symbol Simbolo di sezione @@ -4518,6 +4526,31 @@ axis Both Entrambi @msg $.evalFile requires a file path $.evalFile richiede un percorso di file @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: il timeout deve essere un numero finito di millisecondi, 0 o più @msg $.evalFile: takes a file path and a timeout $.evalFile: accetta un percorso di file e un timeout +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} non è definito +@msg cannot read property '{key}' of {base} impossibile leggere la proprietà '{key}' di {base} +@msg cannot set property '{key}' of {base} impossibile impostare la proprietà '{key}' di {base} +@msg cannot read a property of {base} impossibile leggere una proprietà di {base} +@msg cannot set a property of {base} impossibile impostare una proprietà di {base} +@msg cannot define property '{key}': {why} impossibile definire la proprietà '{key}': {why} +@msg cannot assign to property '{key}': {why} impossibile assegnare alla proprietà '{key}': {why} +@msg cannot delete property '{key}' impossibile eliminare la proprietà '{key}' +@msg cannot declare function {ident} impossibile dichiarare la funzione {ident} +@msg invalid assignment target destinazione di assegnazione non valida +@msg the array's length is read-only la lunghezza dell'array è di sola lettura +@msg the property cannot be redefined la proprietà non può essere ridefinita +@msg the object is not extensible l'oggetto non è estensibile +@msg the length cannot be redefined la lunghezza non può essere ridefinita +@msg it is read-only è di sola lettura +@msg an element cannot be deleted un elemento non può essere eliminato +@msg it has only a getter ha solo un getter +@msg the value is a primitive il valore è primitivo @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: riga {line}, colonna {column} di {file}: {e} (generato) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: riga {line}, colonna {column}: {e} (generato) @msg {name}: {e} (thrown) {name}: {e} (generato) @@ -4623,6 +4656,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato @msg Downloaded {what} Scaricato {what} @msg Expand Appearance: the selection has a basic appearance Espandi aspetto: la selezione ha un aspetto di base +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alcuni effetti raster non sono stati trasformati in immagini: richiederebbero più di 1.024 immagini o 256 megapixel in totale @msg Expand: no brush strokes selected Espandi: nessuna traccia di pennello selezionata @msg Expand: no gradient fills Espandi: nessun riempimento con sfumatura @msg Expand: nothing to expand Espandi: niente da espandere @@ -5948,7 +5982,7 @@ lighting Light Luce @msg Unknown dimension style Stile di quota sconosciuto @msg Unknown unit Unità sconosciuta # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Chiude le estremità circolari dei profili aperti. Le rotazioni parziali mantengono aperti i lati di taglio. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Chiude le estremità circolari dei profili aperti. Le rotazioni parziali chiudono anche i lati di taglio. Distance Distanza @msg span must be "object" or "selection", got {v} span deve essere "object" o "selection", non {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" posiziona un `gradient`, non un campione @@ -6100,6 +6134,7 @@ lighting Light Luce Single Word Justification: Giustificazione parola singola: Full Justify Giustificazione completa Minimum must not exceed Desired, nor Desired Maximum. Il minimo non può superare il valore desiderato, né il desiderato il massimo. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: il minimo non può superare il valore desiderato, né il desiderato il massimo Minimum Minimo Justification Giustificazione Add filters from the list above Aggiungi filtri dall'elenco sopra @@ -7046,6 +7081,24 @@ breakText Glyphs Glifi # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Espandi trattini in tracciati @msg select paths with dashed strokes to expand seleziona tracciati con traccia tratteggiata da espandere +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Cerchio tangente… + Tangent Circle Cerchio tangente + Circle: Cerchio: +@msg `ids` names an object twice `ids` indica due volte lo stesso oggetto +@msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti +@msg `radius` must be from 0.01 to 1000000 pt `radius` deve essere da 0.01 a 1000000 pt +@msg two shapes need a `radius` due forme richiedono un `radius` +@msg three shapes set the radius themselves: leave `radius` out tre forme fissano da sole il raggio: ometti `radius` +@msg `circle` must be from 0 to 64 `circle` deve essere da 0 a 64 +@msg a shape has no outline una forma non ha contorno +@msg the shapes are too complex: at most 2000 segments in all le forme sono troppo complesse: al massimo 2000 segmenti in tutto +@msg these shapes take too long to search la ricerca richiede troppo tempo per queste forme +@msg more than 64 circles touch these shapes: they may touch along a whole curve più di 64 cerchi toccano queste forme: potrebbero toccarle lungo un’intera curva +@msg no circle touches these shapes nessun cerchio tocca queste forme +@msg `circle` is past the last circle found ({found}) `circle` va oltre l’ultimo cerchio trovato ({found}) +@msg object {value} is not a path or compound path l’oggetto {value} non è un tracciato né un tracciato composto +@msg these shapes are too small to measure queste forme sono troppo piccole per essere misurate # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Strumenti documento Save a Timestamped Copy Salva una copia con data e ora @@ -7100,7 +7153,7 @@ breakText Glyphs Glifi @msg stroke cannot be set on a symbol instance stroke non può essere impostato su un’istanza di simbolo @msg fill on a symbol instance must be a solid color or none il fill di un’istanza di simbolo deve essere un colore pieno o none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} non può essere impostato su un’immagine senza l’effetto Converti in forma o Contorna oggetto -@msg pass newName, registration, exportType, nineSlice and/or type specifica newName, registration, exportType, nineSlice e/o type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid specifica newName, registration, exportType, nineSlice, type e/o alignToPixelGrid Text Flow Flusso del testo By Rows Per righe By Columns Per colonne @@ -8698,7 +8751,9 @@ breakText Glyphs Glifi @msg position must be normal, superscript or subscript position deve essere normal, superscript o subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position deve essere topLeft, topRight, bottomLeft o bottomRight @msg positions must be between 0 and 100000 pt le posizioni devono essere comprese tra 0 e 100000 pt +@msg ppi can't be more than {max} for this image ppi non può superare {max} per questa immagine @msg ppi must be a positive number, not {ppi} ppi deve essere un numero positivo, non {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim mantiene i pixel dell'immagine così come sono: ometti ppi @msg ppi must be between 1 and 2400 ppi deve essere compreso tra 1 e 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` non è transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape deve essere clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e8893fb463..22f1125a1a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -49,6 +49,10 @@ font-technology Variable バリアブル Cap Height キャップハイト x-Height x ハイト ICF Box 平均字面 + Show Sample サンプルを表示 + Hide Sample サンプルを隠す + Max Ascent/Descent 最大アセント/ディセント + Max Ascender 最大アセンダ Proportional Metrics プロポーショナルメトリクス H or V Style 横組み・縦組み用かな Roman Italics 欧文イタリック @@ -1862,6 +1866,8 @@ antiAlias Sharp シャープ Folder フォルダー Folder Name: フォルダー名: Font List フォントリスト + Show Similar Fonts 類似フォントを表示 + Clear Similar Fonts 類似フォントの表示を解除 Font Preview Size フォントプレビューのサイズ Font: フォント: Fonts フォント @@ -3195,6 +3201,8 @@ mark-style Japanese 日本式 @msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください Search commands and tools コマンドとツールを検索 Search commands and tools… コマンドとツールを検索… + Recent Commands 最近使ったコマンド + No recent commands 最近使ったコマンドはありません Secondary セカンダリ Select All Art on Layer レイヤー上のすべてのアートを選択 Select All Assets すべてのアセットを選択 @@ -4617,6 +4625,7 @@ swatch Bright Violet ビビッドバイオレット @msg no history to clear 消去するヒストリーがありません @msg no history state {v} ヒストリーの状態 {v} はありません @msg Expand Appearance: the selection has a basic appearance アピアランスを分割: 選択範囲は基本アピアランスです +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 一部のラスター効果は画像になりませんでした: 1,024 枚または合計 256 メガピクセルを超えるためです @msg select (or target) objects whose appearance isn't basic 基本アピアランスではないオブジェクトを選択するか、ターゲットに指定してください @msg {C}: no effect at index {from} {C}: インデックス {from} に効果がありません @msg Expand: no gradient fills 拡張: グラデーションの塗りがありません @@ -5285,6 +5294,31 @@ swatch Bright Violet ビビッドバイオレット @msg $.evalFile requires a file path $.evalFile にはファイルパスが必要です @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: タイムアウトは 0 以上の有限のミリ秒数にしてください @msg $.evalFile: takes a file path and a timeout $.evalFile: ファイルパスとタイムアウトを指定します +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} は定義されていません +@msg cannot read property '{key}' of {base} {base} のプロパティ '{key}' を読み取れません +@msg cannot set property '{key}' of {base} {base} のプロパティ '{key}' を設定できません +@msg cannot read a property of {base} {base} のプロパティを読み取れません +@msg cannot set a property of {base} {base} のプロパティを設定できません +@msg cannot define property '{key}': {why} プロパティ '{key}' を定義できません: {why} +@msg cannot assign to property '{key}': {why} プロパティ '{key}' に代入できません: {why} +@msg cannot delete property '{key}' プロパティ '{key}' を削除できません +@msg cannot declare function {ident} 関数 {ident} を宣言できません +@msg invalid assignment target 代入先が無効です +@msg the array's length is read-only 配列の長さは読み取り専用です +@msg the property cannot be redefined プロパティは再定義できません +@msg the object is not extensible オブジェクトは拡張できません +@msg the length cannot be redefined 長さは再定義できません +@msg it is read-only 読み取り専用です +@msg an element cannot be deleted 要素は削除できません +@msg it has only a getter ゲッターしかありません +@msg the value is a primitive 値はプリミティブです @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file} の {line} 行目、{column} 列目: {e} (スロー) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line} 行目、{column} 列目: {e} (スロー) @msg {name}: {e} (thrown) {name}: {e} (スロー) @@ -5993,7 +6027,7 @@ lighting Light ライト @msg Unknown dimension style 寸法のスタイルが不明です @msg Unknown unit 単位が不明です # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 開いたプロファイルの円形の端を閉じます。部分的な回転では切断面は開いたままです。 + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 開いたプロファイルの円形の端を閉じます。部分的な回転では切断面も閉じます。 Distance 距離 @msg span must be "object" or "selection", got {v} span は "object" または "selection" で指定してください ({v} は指定できません) @msg span: "selection" places a `gradient`, not a swatch span: "selection" は `gradient` を配置します。スウォッチは配置できません @@ -6147,6 +6181,7 @@ lighting Light ライト Single Word Justification: 単語のみの行の揃え: Full Justify 両端揃え Minimum must not exceed Desired, nor Desired Maximum. 最小値は最適値を、最適値は最大値を超えることはできません。 +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: 最小値は最適値を、最適値は最大値を超えることはできません Minimum 最小 Justification 文字組み Add filters from the list above 上のリストからフィルターを追加 @@ -7899,7 +7934,9 @@ axis Y Axis Y 軸 @msg position must be normal, superscript or subscript position には normal、superscript、subscript のいずれかを指定してください @msg position must be topLeft, topRight, bottomLeft or bottomRight position には topLeft、topRight、bottomLeft、bottomRight のいずれかを指定してください @msg positions must be between 0 and 100000 pt positions には 0 から 100000 pt までの値を指定してください +@msg ppi can't be more than {max} for this image この画像の ppi には {max} 以下の値を指定してください @msg ppi must be a positive number, not {ppi} ppi には正の数値を指定してください ({ppi} は指定できません) +@msg trim keeps the image's pixels as they are: leave out ppi trim は画像のピクセルをそのまま残します: ppi は指定しないでください @msg ppi must be between 1 and 2400 ppi には 1 から 2400 までの値を指定してください @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` は transforms|bounds|fileDimensions|fit|fill のいずれでもありません @msg preserveShape must be clippingMask|transparency preserveShape には clippingMask|transparency のいずれかを指定してください @@ -8923,6 +8960,24 @@ breakText Glyphs 字形 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 破線をパスに拡張 @msg select paths with dashed strokes to expand 拡張する破線のパスを選択してください +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… 接円… + Tangent Circle 接円 + Circle: 円: +@msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています +@msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください +@msg `radius` must be from 0.01 to 1000000 pt `radius` は 0.01 から 1000000 pt にしてください +@msg two shapes need a `radius` 2 つのシェイプには `radius` が必要です +@msg three shapes set the radius themselves: leave `radius` out 3 つのシェイプでは半径が決まるため、`radius` は指定しないでください +@msg `circle` must be from 0 to 64 `circle` は 0 から 64 にしてください +@msg a shape has no outline アウトラインのないシェイプがあります +@msg the shapes are too complex: at most 2000 segments in all シェイプが複雑すぎます:セグメントは合計 2000 個までです +@msg these shapes take too long to search これらのシェイプの検索に時間がかかりすぎます +@msg more than 64 circles touch these shapes: they may touch along a whole curve これらのシェイプに接する円が 64 個を超えています:曲線全体に沿って接している可能性があります +@msg no circle touches these shapes これらのシェイプに接する円はありません +@msg `circle` is past the last circle found ({found}) `circle` が見つかった最後の円を超えています({found}) +@msg object {value} is not a path or compound path オブジェクト {value} はパスでも複合パスでもありません +@msg these shapes are too small to measure これらのシェイプは小さすぎて測定できません # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools ドキュメントツール Save a Timestamped Copy 日時付きのコピーを保存 @@ -8977,7 +9032,7 @@ breakText Glyphs 字形 @msg stroke cannot be set on a symbol instance シンボルインスタンスには stroke を設定できません @msg fill on a symbol instance must be a solid color or none シンボルインスタンスの fill は単色または none にしてください @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 「シェイプに変換」または「オブジェクトのアウトライン」効果のない画像には {key} を設定できません -@msg pass newName, registration, exportType, nineSlice and/or type newName、registration、exportType、nineSlice、type のいずれかを指定してください +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName、registration、exportType、nineSlice、type、alignToPixelGrid のいずれかを指定してください Text Flow テキストの流れ By Rows 行方向 By Columns 列方向 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 85f6b2c074..73927f2187 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3670,6 +3670,10 @@ digits Malayalam მალაიალამური Em Box Em-ბლოკი x-Height x-სიმაღლე ICF Box ICF-ბლოკი + Show Sample ნიმუშის ჩვენება + Hide Sample ნიმუშის დამალვა + Max Ascent/Descent მაქს. სიმაღლე/სიღრმე + Max Ascender მაქს. ზედა გამონაშვერი Copy Color Value (Hex) ფერის მნიშვნელობის კოპირება (Hex) Create New Swatch… ახალი ფერის ნიმუშის შექმნა… Name 40% სახელი 40% @@ -5351,6 +5355,8 @@ theme Appearance იერსახე Find Font Files შრიფტის ფაილების ძებნა Add Font Files შრიფტის ფაილების დამატება Font List შრიფტების სია + Show Similar Fonts მსგავსი შრიფტების ჩვენება + Clear Similar Fonts მსგავსი შრიფტების გასუფთავება Fonts in Document დოკუმენტის შრიფტები Refresh Font List შრიფტების სიის განახლება Replace Font შრიფტის ჩანაცვლება @@ -6078,6 +6084,8 @@ font-technology Variable ცვლადი Saving შენახვა Saving {} ინახება: {} Search commands and tools… ბრძანებებისა და ხელსაწყოების ძიება… + Recent Commands ბოლო ბრძანებები + No recent commands ბოლო ბრძანებები არ არის Dashed Line ტირეებიანი ხაზი Panel menu პანელის მენიუ Unembed… ჩაშენების მოხსნა… @@ -6339,6 +6347,7 @@ font-technology Variable ცვლადი @msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია @msg Downloaded {what} ჩამოტვირთულია: {what} @msg Expand Appearance: the selection has a basic appearance იერსახის გაშლა: მონიშნულს საბაზისო იერსახე აქვს +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all ზოგიერთი რასტრული ეფექტი გამოსახულებად არ გადაიქცა: მათ დასჭირდებოდა 1024-ზე მეტი გამოსახულება ან ჯამში 256 მეგაპიქსელი @msg Expand: no brush strokes selected გაშლა: ფუნჯის შტრიხები მონიშნული არ არის @msg Expand: no gradient fills გაშლა: გრადიენტული შევსებები არ არის @msg Expand: nothing to expand გაშლა: გასაშლელი არაფერია @@ -7783,6 +7792,31 @@ imageTrace Outline კონტური @msg $.evalFile requires a file path $.evalFile-ს სჭირდება ფაილის მისამართი @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: დროის ლიმიტი უნდა იყოს მილიწამების სასრული რიცხვი, 0 ან მეტი @msg $.evalFile: takes a file path and a timeout $.evalFile: იღებს ფაილის მისამართს და დროის ლიმიტს +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} არ არის განსაზღვრული +@msg cannot read property '{key}' of {base} {base} მნიშვნელობის თვისება '{key}' ვერ წაიკითხება +@msg cannot set property '{key}' of {base} {base} მნიშვნელობის თვისება '{key}' ვერ დაყენდება +@msg cannot read a property of {base} {base} მნიშვნელობის თვისება ვერ წაიკითხება +@msg cannot set a property of {base} {base} მნიშვნელობის თვისება ვერ დაყენდება +@msg cannot define property '{key}': {why} თვისება '{key}' ვერ განისაზღვრება: {why} +@msg cannot assign to property '{key}': {why} თვისებას '{key}' მნიშვნელობა ვერ მიენიჭება: {why} +@msg cannot delete property '{key}' თვისება '{key}' ვერ წაიშლება +@msg cannot declare function {ident} ფუნქცია {ident} ვერ გამოცხადდება +@msg invalid assignment target მინიჭების არასწორი სამიზნე +@msg the array's length is read-only მასივის სიგრძე მხოლოდ წასაკითხია +@msg the property cannot be redefined თვისება ხელახლა ვერ განისაზღვრება +@msg the object is not extensible ობიექტი არ არის გაფართოებადი +@msg the length cannot be redefined სიგრძე ხელახლა ვერ განისაზღვრება +@msg it is read-only ის მხოლოდ წასაკითხია +@msg an element cannot be deleted ელემენტი ვერ წაიშლება +@msg it has only a getter მას მხოლოდ getter აქვს +@msg the value is a primitive მნიშვნელობა პრიმიტიულია @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (გამონაკლისი) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: სტრიქონი {line}, სვეტი {column}: {e} (გამონაკლისი) @msg {name}: {e} (thrown) {name}: {e} (გამონაკლისი) @@ -8035,7 +8069,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg Unknown dimension orientation ზომის უცნობი ორიენტაცია @msg Unknown dimension style ზომის უცნობი სტილი @msg Unknown unit უცნობი ერთეული - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეები ღია რჩება. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. ღია პროფილების წრიული ბოლოების დახურვა. ნაწილობრივი ბრუნვისას ჭრის მხარეებიც იხურება. Distance მანძილი # Upstream sync 2026-10-16 (2): Smart Blur modes, Layers panel filter, Color panel options, templates, PostScript files. Mode რეჟიმი @@ -9535,6 +9569,24 @@ breakText Glyphs გლიფები # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths ტირეების ტრაექტორიებად გაშლა @msg select paths with dashed strokes to expand აირჩიეთ გასაშლელი ტირეებიანი ხაზის კონტურები +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… მხები წრე… + Tangent Circle მხები წრე + Circle: წრე: +@msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს +@msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია +@msg `radius` must be from 0.01 to 1000000 pt `radius` უნდა იყოს 0.01-დან 1000000 pt-მდე +@msg two shapes need a `radius` ორ ფიგურას `radius` სჭირდება +@msg three shapes set the radius themselves: leave `radius` out სამი ფიგურა რადიუსს თავად ადგენს: გამოტოვეთ `radius` +@msg `circle` must be from 0 to 64 `circle` უნდა იყოს 0-დან 64-მდე +@msg a shape has no outline ერთ-ერთ ფიგურას კონტური არ აქვს +@msg the shapes are too complex: at most 2000 segments in all ფიგურები ზედმეტად რთულია: სულ არაუმეტეს 2000 სეგმენტი +@msg these shapes take too long to search ამ ფიგურების ძიებას ზედმეტად დიდი დრო სჭირდება +@msg more than 64 circles touch these shapes: they may touch along a whole curve ამ ფიგურებს 64-ზე მეტი წრე ეხება: შესაძლოა მთელი მრუდის გასწვრივ ეხებოდნენ +@msg no circle touches these shapes ამ ფიგურებს არცერთი წრე არ ეხება +@msg `circle` is past the last circle found ({found}) `circle` ბოლო ნაპოვნი წრის შემდეგაა ({found}) +@msg object {value} is not a path or compound path ობიექტი {value} არ არის ტრაექტორია ან შედგენილი ტრაექტორია +@msg these shapes are too small to measure ეს ფიგურები ზედმეტად პატარაა გასაზომად # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools დოკუმენტის ხელსაწყოები Save a Timestamped Copy ასლის შენახვა თარიღითა და დროით @@ -9608,7 +9660,7 @@ breakText Glyphs გლიფები @msg stroke cannot be set on a symbol instance stroke ვერ დაყენდება სიმბოლოს ეგზემპლარზე @msg fill on a symbol instance must be a solid color or none სიმბოლოს ეგზემპლარის fill უნდა იყოს ერთფეროვანი ფერი ან none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} ვერ დაყენდება გამოსახულებაზე „ფიგურად გარდაქმნის“ ან „ობიექტის კონტურებად გარდაქმნის“ ეფექტის გარეშე -@msg pass newName, registration, exportType, nineSlice and/or type მიუთითეთ newName, registration, exportType, nineSlice და/ან type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid მიუთითეთ newName, registration, exportType, nineSlice, type და/ან alignToPixelGrid Text Flow ტექსტის დინება By Rows სტრიქონების მიხედვით By Columns სვეტების მიხედვით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 62ed44851f..fa9e6e7894 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -43,6 +43,10 @@ font-technology Variable 가변 Cap Height 대문자 높이 x-Height x 높이 ICF Box ICF 박스 + Show Sample 샘플 표시 + Hide Sample 샘플 숨기기 + Max Ascent/Descent 최대 어센트/디센트 + Max Ascender 최대 어센더 Proportional Metrics 비례 메트릭 H or V Style 가로 또는 세로 스타일 Roman Italics 로마자 이탤릭 @@ -1852,6 +1856,8 @@ antiAlias Sharp 날카롭게 Folder 폴더 Folder Name: 폴더 이름: Font List 글꼴 목록 + Show Similar Fonts 유사한 글꼴 표시 + Clear Similar Fonts 유사한 글꼴 지우기 Font Preview Size 글꼴 미리 보기 크기 Font: 글꼴: Fonts 글꼴 @@ -3184,6 +3190,8 @@ mark-style Japanese 일본식 @msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1} Search commands and tools 명령 및 도구 검색 Search commands and tools… 명령 및 도구 검색… + Recent Commands 최근 명령 + No recent commands 최근 명령 없음 Secondary 보조 Select All Art on Layer 레이어의 모든 아트웍 선택 Select All Assets 모든 에셋 선택 @@ -4544,6 +4552,7 @@ theme Appearance 외관 @msg no history to clear 지울 히스토리가 없습니다 @msg no history state {v} 히스토리 상태 {v}이(가) 없습니다 @msg Expand Appearance: the selection has a basic appearance 모양새 확장: 선택 항목은 기본 모양새입니다 +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 일부 래스터 효과는 이미지로 만들지 않았습니다: 이미지 1,024개 또는 총 256메가픽셀을 넘기 때문입니다 @msg select (or target) objects whose appearance isn't basic 모양새가 기본이 아닌 개체를 선택(또는 대상 지정)하세요 @msg {C}: no effect at index {from} {C}: 인덱스 {from}에 효과가 없습니다 @msg Expand: no gradient fills 확장: 그레이디언트 칠이 없습니다 @@ -5212,6 +5221,31 @@ theme Appearance 외관 @msg $.evalFile requires a file path $.evalFile에는 파일 경로가 필요합니다 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: 시간 제한은 0 이상의 유한한 밀리초 수여야 합니다 @msg $.evalFile: takes a file path and a timeout $.evalFile: 파일 경로와 시간 제한을 받습니다 +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident}이(가) 정의되지 않았습니다 +@msg cannot read property '{key}' of {base} {base}의 속성 '{key}'을(를) 읽을 수 없습니다 +@msg cannot set property '{key}' of {base} {base}의 속성 '{key}'을(를) 설정할 수 없습니다 +@msg cannot read a property of {base} {base}의 속성을 읽을 수 없습니다 +@msg cannot set a property of {base} {base}의 속성을 설정할 수 없습니다 +@msg cannot define property '{key}': {why} 속성 '{key}'을(를) 정의할 수 없습니다: {why} +@msg cannot assign to property '{key}': {why} 속성 '{key}'에 대입할 수 없습니다: {why} +@msg cannot delete property '{key}' 속성 '{key}'을(를) 삭제할 수 없습니다 +@msg cannot declare function {ident} 함수 {ident}을(를) 선언할 수 없습니다 +@msg invalid assignment target 대입 대상이 잘못되었습니다 +@msg the array's length is read-only 배열의 길이는 읽기 전용입니다 +@msg the property cannot be redefined 속성을 다시 정의할 수 없습니다 +@msg the object is not extensible 객체를 확장할 수 없습니다 +@msg the length cannot be redefined 길이를 다시 정의할 수 없습니다 +@msg it is read-only 읽기 전용입니다 +@msg an element cannot be deleted 요소를 삭제할 수 없습니다 +@msg it has only a getter getter만 있습니다 +@msg the value is a primitive 값이 원시 값입니다 @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}의 {line}행 {column}열: {e} (발생) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line}행 {column}열: {e} (발생) @msg {name}: {e} (thrown) {name}: {e} (발생) @@ -5910,7 +5944,7 @@ lighting Light 광원 @msg Unknown dimension style 알 수 없는 치수 스타일 @msg Unknown unit 알 수 없는 단위 # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 열린 프로파일의 원형 끝을 닫습니다. 부분 회전에서는 절단 측면이 열린 상태로 유지됩니다. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 열린 프로파일의 원형 끝을 닫습니다. 부분 회전에서는 절단 측면도 닫힙니다. Distance 거리 @msg span must be "object" or "selection", got {v} span은 "object" 또는 "selection"이어야 합니다. {v}은(는) 사용할 수 없습니다 @msg span: "selection" places a `gradient`, not a swatch span: "selection"은 `gradient`를 배치합니다. 견본은 배치할 수 없습니다 @@ -6064,6 +6098,7 @@ lighting Light 광원 Single Word Justification: 단일 단어 정렬: Full Justify 강제 양쪽 정렬 Minimum must not exceed Desired, nor Desired Maximum. 최소값은 희망값을, 희망값은 최대값을 넘을 수 없습니다. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: 최소값은 희망값을, 희망값은 최대값을 넘을 수 없습니다 Minimum 최소 Justification 양끝 맞춤 Add filters from the list above 위 목록에서 필터 추가 @@ -7010,6 +7045,24 @@ breakText Glyphs 글리프 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 대시를 패스로 확장 @msg select paths with dashed strokes to expand 확장할 점선 획의 패스를 선택하십시오 +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… 접원… + Tangent Circle 접원 + Circle: 원: +@msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 +@msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 +@msg `radius` must be from 0.01 to 1000000 pt `radius`은(는) 0.01에서 1000000 pt 사이여야 합니다 +@msg two shapes need a `radius` 모양 두 개에는 `radius`이(가) 필요합니다 +@msg three shapes set the radius themselves: leave `radius` out 모양 세 개는 반지름을 스스로 정하므로 `radius`을(를) 빼세요 +@msg `circle` must be from 0 to 64 `circle`은(는) 0에서 64 사이여야 합니다 +@msg a shape has no outline 윤곽선이 없는 모양이 있습니다 +@msg the shapes are too complex: at most 2000 segments in all 모양이 너무 복잡합니다: 세그먼트는 모두 합쳐 최대 2000개입니다 +@msg these shapes take too long to search 이 모양들을 찾는 데 시간이 너무 오래 걸립니다 +@msg more than 64 circles touch these shapes: they may touch along a whole curve 이 모양들에 닿는 원이 64개를 넘습니다: 곡선 전체를 따라 닿아 있을 수 있습니다 +@msg no circle touches these shapes 이 모양들에 닿는 원이 없습니다 +@msg `circle` is past the last circle found ({found}) `circle`이(가) 찾은 마지막 원을 넘었습니다({found}) +@msg object {value} is not a path or compound path 오브젝트 {value}은(는) 패스나 컴파운드 패스가 아닙니다 +@msg these shapes are too small to measure 이 모양들은 너무 작아서 측정할 수 없습니다 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 문서 도구 Save a Timestamped Copy 날짜와 시간이 붙은 사본 저장 @@ -7064,7 +7117,7 @@ breakText Glyphs 글리프 @msg stroke cannot be set on a symbol instance 심볼 인스턴스에는 stroke를 설정할 수 없습니다 @msg fill on a symbol instance must be a solid color or none 심볼 인스턴스의 fill은 단색 또는 none이어야 합니다 @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 모양으로 변환 또는 개체 윤곽선화 효과가 없는 이미지에는 {key}을(를) 설정할 수 없습니다 -@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice 및/또는 type을 지정하세요 +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type 및/또는 alignToPixelGrid을 지정하세요 Text Flow 텍스트 흐름 By Rows 행 방향 By Columns 열 방향 @@ -8664,7 +8717,9 @@ breakText Glyphs 글리프 @msg position must be normal, superscript or subscript position은 normal, superscript 또는 subscript여야 합니다 @msg position must be topLeft, topRight, bottomLeft or bottomRight position은 topLeft, topRight, bottomLeft 또는 bottomRight여야 합니다 @msg positions must be between 0 and 100000 pt positions는 0에서 100000 pt 사이여야 합니다 +@msg ppi can't be more than {max} for this image 이 이미지의 ppi는 {max}보다 클 수 없습니다 @msg ppi must be a positive number, not {ppi} ppi는 양수여야 합니다: {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim은 이미지의 픽셀을 그대로 유지합니다: ppi를 지정하지 마세요 @msg ppi must be between 1 and 2400 ppi는 1에서 2400 사이여야 합니다 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`은(는) transforms|bounds|fileDimensions|fit|fill이 아닙니다 @msg preserveShape must be clippingMask|transparency preserveShape는 clippingMask|transparency여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a55defb184..ca5847f153 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -91,6 +91,31 @@ @msg $.evalFile requires a file path $.evalFile vereist een bestandspad @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: de time-out moet een eindig aantal milliseconden zijn, 0 of meer @msg $.evalFile: takes a file path and a timeout $.evalFile: verwacht een bestandspad en een time-out +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} is niet gedefinieerd +@msg cannot read property '{key}' of {base} kan eigenschap '{key}' van {base} niet lezen +@msg cannot set property '{key}' of {base} kan eigenschap '{key}' van {base} niet instellen +@msg cannot read a property of {base} kan geen eigenschap van {base} lezen +@msg cannot set a property of {base} kan geen eigenschap van {base} instellen +@msg cannot define property '{key}': {why} kan eigenschap '{key}' niet definiëren: {why} +@msg cannot assign to property '{key}': {why} kan niet toewijzen aan eigenschap '{key}': {why} +@msg cannot delete property '{key}' kan eigenschap '{key}' niet verwijderen +@msg cannot declare function {ident} kan functie {ident} niet declareren +@msg invalid assignment target ongeldig toewijzingsdoel +@msg the array's length is read-only de lengte van de array is alleen-lezen +@msg the property cannot be redefined de eigenschap kan niet opnieuw worden gedefinieerd +@msg the object is not extensible het object is niet uitbreidbaar +@msg the length cannot be redefined de lengte kan niet opnieuw worden gedefinieerd +@msg it is read-only deze is alleen-lezen +@msg an element cannot be deleted een element kan niet worden verwijderd +@msg it has only a getter deze heeft alleen een getter +@msg the value is a primitive de waarde is primitief @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: regel {line}, kolom {column} van {file}: {e} (opgeworpen) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: regel {line}, kolom {column}: {e} (opgeworpen) @msg {name}: {e} (thrown) {name}: {e} (opgeworpen) @@ -2188,6 +2213,10 @@ digits Malayalam Malayalam Em Box Em-vak x-Height x-hoogte ICF Box ICF-vak + Show Sample Voorbeeld tonen + Hide Sample Voorbeeld verbergen + Max Ascent/Descent Max. hoogte/diepte + Max Ascender Max. stijger Copy Color Value (Hex) Kleurwaarde kopiëren (Hex) Create New Swatch… Nieuw staal maken… Name 40% Naam 40% @@ -3961,6 +3990,8 @@ theme Appearance Vormgeving Find Font Files Lettertypebestanden zoeken Add Font Files Lettertypebestanden toevoegen Font List Lettertypelijst + Show Similar Fonts Vergelijkbare lettertypen tonen + Clear Similar Fonts Vergelijkbare lettertypen wissen Fonts in Document Lettertypen in document Refresh Font List Lettertypelijst vernieuwen Replace Font Lettertype vervangen @@ -4716,6 +4747,8 @@ font-technology Variable Variabel Saving Bezig met opslaan Saving {} {} wordt opgeslagen Search commands and tools… Opdrachten en gereedschappen zoeken… + Recent Commands Recente opdrachten + No recent commands Geen recente opdrachten Dashed Line Streepjeslijn Panel menu Paneelmenu Unembed… Insluiten ongedaan maken… @@ -4995,6 +5028,7 @@ imageTrace Outline Contour @msg Divide Objects Below: select exactly one path Objecten eronder verdelen: selecteer precies één pad @msg Downloaded {what} {what} gedownload @msg Expand Appearance: the selection has a basic appearance Vormgeving uitbreiden: de selectie heeft een basisvormgeving +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all sommige rastereffecten zijn niet omgezet in afbeeldingen: ze zouden meer dan 1.024 afbeeldingen of in totaal 256 megapixel nodig hebben @msg Expand: no brush strokes selected Uitbreiden: geen penseelstreken geselecteerd @msg Expand: no gradient fills Uitbreiden: geen verloopvullingen @msg Expand: nothing to expand Uitbreiden: niets om uit te breiden @@ -6984,7 +7018,9 @@ imageTrace Outline Contour @msg position must be normal, superscript or subscript position moet normal, superscript of subscript zijn @msg position must be topLeft, topRight, bottomLeft or bottomRight position moet topLeft, topRight, bottomLeft of bottomRight zijn @msg positions must be between 0 and 100000 pt positions moeten tussen 0 en 100000 pt liggen +@msg ppi can't be more than {max} for this image ppi kan voor deze afbeelding niet hoger zijn dan {max} @msg ppi must be a positive number, not {ppi} ppi moet een positief getal zijn, niet {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim laat de pixels van de afbeelding zoals ze zijn: laat ppi weg @msg ppi must be between 1 and 2400 ppi moet tussen 1 en 2400 liggen @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` is niet transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape moet clippingMask|transparency zijn @@ -8137,7 +8173,7 @@ mark-style Japanese Japans @msg Unknown dimension orientation Onbekende maatlijnrichting @msg Unknown dimension style Onbekende maatlijnstijl @msg Unknown unit Onbekende eenheid - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen houden hun afgesneden zijden open. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Sluit de ronde uiteinden van open profielen. Gedeeltelijke omwentelingen sluiten ook hun afgesneden zijden. Darkness Donkerte Isolate Selected Object Geselecteerd object isoleren Keep selected Geselecteerd houden @@ -8584,6 +8620,7 @@ swatch Bright Violet Felviolet Single Word Justification: Uitvullen van één woord: Full Justify Volledig uitvullen Minimum must not exceed Desired, nor Desired Maximum. Minimum mag niet groter zijn dan Gewenst, en Gewenst niet groter dan Maximum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum mag niet groter zijn dan Gewenst, en Gewenst niet groter dan Maximum Justification Uitvullen Add filters from the list above Voeg filters toe uit de lijst hierboven Add to Stack Toevoegen aan stapel @@ -9293,6 +9330,24 @@ breakText Glyphs Glyphs # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Streepjes uitbreiden tot paden @msg select paths with dashed strokes to expand selecteer paden met een streepjeslijn om uit te breiden +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Raakcirkel… + Tangent Circle Raakcirkel + Circle: Cirkel: +@msg `ids` names an object twice `ids` noemt een object twee keer +@msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden +@msg `radius` must be from 0.01 to 1000000 pt `radius` moet van 0.01 tot 1000000 pt zijn +@msg two shapes need a `radius` twee vormen hebben een `radius` nodig +@msg three shapes set the radius themselves: leave `radius` out drie vormen bepalen de straal zelf: laat `radius` weg +@msg `circle` must be from 0 to 64 `circle` moet van 0 tot 64 zijn +@msg a shape has no outline een vorm heeft geen omtrek +@msg the shapes are too complex: at most 2000 segments in all de vormen zijn te complex: hoogstens 2000 segmenten in totaal +@msg these shapes take too long to search het zoeken duurt te lang voor deze vormen +@msg more than 64 circles touch these shapes: they may touch along a whole curve meer dan 64 cirkels raken deze vormen: ze raken ze misschien langs een hele kromme +@msg no circle touches these shapes geen enkele cirkel raakt deze vormen +@msg `circle` is past the last circle found ({found}) `circle` ligt voorbij de laatst gevonden cirkel ({found}) +@msg object {value} is not a path or compound path object {value} is geen pad of samengesteld pad +@msg these shapes are too small to measure deze vormen zijn te klein om te meten # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Documentgereedschappen Save a Timestamped Copy Een kopie met tijdstempel opslaan @@ -9347,7 +9402,7 @@ breakText Glyphs Glyphs @msg stroke cannot be set on a symbol instance stroke kan niet worden ingesteld op een symboolinstantie @msg fill on a symbol instance must be a solid color or none fill van een symboolinstantie moet een egale kleur of none zijn @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan niet worden ingesteld op een afbeelding zonder het effect Converteren naar vorm of Object omtrekken -@msg pass newName, registration, exportType, nineSlice and/or type geef newName, registration, exportType, nineSlice en/of type op +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid geef newName, registration, exportType, nineSlice, type en/of alignToPixelGrid op Text Flow Tekstdoorloop By Rows Per rij By Columns Per kolom diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2bed923406..f899e84032 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1661,6 +1661,10 @@ digits Malayalam Malajalam Em Box Ramka firetowa x-Height Wysokość x ICF Box Ramka ICF + Show Sample Pokaż próbkę + Hide Sample Ukryj próbkę + Max Ascent/Descent Maks. wysokość/głębokość + Max Ascender Maks. wydłużenie górne Copy Color Value (Hex) Kopiuj wartość koloru (hex) Create New Swatch… Utwórz nową próbkę… Name 40% Nazwa 40% @@ -3576,6 +3580,8 @@ theme Appearance Wygląd Find Font Files Znajdź pliki czcionek Add Font Files Dodaj pliki czcionek Font List Lista czcionek + Show Similar Fonts Pokaż podobne czcionki + Clear Similar Fonts Wyczyść podobne czcionki Fonts in Document Czcionki w dokumencie Refresh Font List Odśwież listę czcionek Replace Font Zastąp czcionkę @@ -4316,6 +4322,8 @@ font-technology Variable Zmienne Saving Zapisywanie Saving {} Zapisywanie {} Search commands and tools… Szukaj poleceń i narzędzi… + Recent Commands Ostatnie polecenia + No recent commands Brak ostatnich poleceń Dashed Line Linia przerywana Panel menu Menu panelu Unembed… Wyodrębnij… @@ -4609,6 +4617,31 @@ imageTrace Outline Kontur @msg $.evalFile requires a file path $.evalFile wymaga ścieżki pliku @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: limit czasu musi być skończoną liczbą milisekund, 0 lub więcej @msg $.evalFile: takes a file path and a timeout $.evalFile: przyjmuje ścieżkę pliku i limit czasu +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} nie jest zdefiniowane +@msg cannot read property '{key}' of {base} nie można odczytać właściwości '{key}' wartości {base} +@msg cannot set property '{key}' of {base} nie można ustawić właściwości '{key}' wartości {base} +@msg cannot read a property of {base} nie można odczytać właściwości wartości {base} +@msg cannot set a property of {base} nie można ustawić właściwości wartości {base} +@msg cannot define property '{key}': {why} nie można zdefiniować właściwości '{key}': {why} +@msg cannot assign to property '{key}': {why} nie można przypisać do właściwości '{key}': {why} +@msg cannot delete property '{key}' nie można usunąć właściwości '{key}' +@msg cannot declare function {ident} nie można zadeklarować funkcji {ident} +@msg invalid assignment target nieprawidłowy cel przypisania +@msg the array's length is read-only długość tablicy jest tylko do odczytu +@msg the property cannot be redefined właściwości nie można zdefiniować ponownie +@msg the object is not extensible obiektu nie można rozszerzać +@msg the length cannot be redefined długości nie można zdefiniować ponownie +@msg it is read-only jest tylko do odczytu +@msg an element cannot be deleted elementu nie można usunąć +@msg it has only a getter ma tylko getter +@msg the value is a primitive wartość jest prymitywna @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: wiersz {line}, kolumna {column} w {file}: {e} (zgłoszony wyjątek) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: wiersz {line}, kolumna {column}: {e} (zgłoszony wyjątek) @msg {name}: {e} (thrown) {name}: {e} (zgłoszony wyjątek) @@ -4714,6 +4747,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę @msg Downloaded {what} Pobrano {what} @msg Expand Appearance: the selection has a basic appearance Rozszerz wygląd: zaznaczenie ma wygląd podstawowy +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all niektóre efekty rastrowe nie zostały zamienione na obrazy: zajęłyby więcej niż 1024 obrazy lub łącznie 256 megapikseli @msg Expand: no brush strokes selected Rozszerz: nie zaznaczono pociągnięć pędzla @msg Expand: no gradient fills Rozszerz: brak wypełnień gradientem @msg Expand: nothing to expand Rozszerz: nie ma czego rozszerzać @@ -6182,7 +6216,7 @@ mark-style Japanese Japońskie @msg Unknown dimension style Nieznany styl wymiaru @msg Unknown unit Nieznana jednostka # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Zamknij okrągłe końce otwartych profili. Przy częściowym obrocie boki przekroju pozostają otwarte. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Zamknij okrągłe końce otwartych profili. Przy częściowym obrocie boki przekroju również zostają zamknięte. Distance Odległość @msg span must be "object" or "selection", got {v} span musi mieć wartość "object" lub "selection", a nie {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" umieszcza `gradient`, a nie próbkę @@ -6336,6 +6370,7 @@ mark-style Japanese Japońskie Single Word Justification: Justowanie pojedynczego wyrazu: Full Justify Pełne justowanie Minimum must not exceed Desired, nor Desired Maximum. Minimum nie może przekraczać wartości optymalnej, a wartość optymalna maksimum. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: minimum nie może przekraczać wartości optymalnej, a wartość optymalna maksimum Justification Justowanie Add filters from the list above Dodaj filtry z listy powyżej Add to Stack Dodaj do stosu @@ -7275,6 +7310,24 @@ breakText Glyphs Glify # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozszerz kreski na ścieżki @msg select paths with dashed strokes to expand zaznacz ścieżki z przerywanym konturem do rozszerzenia +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Okrąg styczny… + Tangent Circle Okrąg styczny + Circle: Okrąg: +@msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy +@msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone +@msg `radius` must be from 0.01 to 1000000 pt `radius` musi wynosić od 0.01 do 1000000 pt +@msg two shapes need a `radius` dwa kształty wymagają `radius` +@msg three shapes set the radius themselves: leave `radius` out trzy kształty same wyznaczają promień: pomiń `radius` +@msg `circle` must be from 0 to 64 `circle` musi wynosić od 0 do 64 +@msg a shape has no outline kształt nie ma konturu +@msg the shapes are too complex: at most 2000 segments in all kształty są zbyt złożone: łącznie najwyżej 2000 segmentów +@msg these shapes take too long to search wyszukiwanie dla tych kształtów trwa zbyt długo +@msg more than 64 circles touch these shapes: they may touch along a whole curve tych kształtów dotyka ponad 64 okręgów: mogą się z nimi stykać wzdłuż całej krzywej +@msg no circle touches these shapes żaden okrąg nie dotyka tych kształtów +@msg `circle` is past the last circle found ({found}) `circle` wykracza poza ostatni znaleziony okrąg ({found}) +@msg object {value} is not a path or compound path obiekt {value} nie jest ścieżką ani ścieżką złożoną +@msg these shapes are too small to measure te kształty są za małe, aby je zmierzyć # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Narzędzia dokumentu Save a Timestamped Copy Zapisz kopię z datą i godziną @@ -7329,7 +7382,7 @@ breakText Glyphs Glify @msg stroke cannot be set on a symbol instance nie można ustawić stroke dla wystąpienia symbolu @msg fill on a symbol instance must be a solid color or none fill wystąpienia symbolu musi być jednolitym kolorem lub none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it nie można ustawić {key} dla obrazu bez efektu Konwertuj na kształt lub Kontur obiektu -@msg pass newName, registration, exportType, nineSlice and/or type podaj newName, registration, exportType, nineSlice i/lub type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid podaj newName, registration, exportType, nineSlice, type i/lub alignToPixelGrid Text Flow Przepływ tekstu By Rows Wierszami By Columns Kolumnami @@ -8938,7 +8991,9 @@ breakText Glyphs Glify @msg position must be normal, superscript or subscript position musi mieć wartość normal, superscript lub subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position musi mieć wartość topLeft, topRight, bottomLeft lub bottomRight @msg positions must be between 0 and 100000 pt positions musi mieścić się w zakresie od 0 do 100000 pt +@msg ppi can't be more than {max} for this image ppi nie może przekraczać {max} dla tego obrazu @msg ppi must be a positive number, not {ppi} ppi musi być liczbą dodatnią, a nie {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim zachowuje piksele obrazu bez zmian: pomiń ppi @msg ppi must be between 1 and 2400 ppi musi mieścić się w zakresie od 1 do 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` nie jest jedną z wartości transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape musi mieć wartość clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 3a2df597b2..14f3aca8c3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -929,6 +929,10 @@ antiAlias Sharp Nítido Em Box Caixa Eme x-Height Altura do x ICF Box Caixa ICF + Show Sample Mostrar Amostra + Hide Sample Ocultar Amostra + Max Ascent/Descent Altura/Profundidade Máx. + Max Ascender Ascendente Máx. Em Dash Travessão Em Space Espaço Em Embed Incorporar @@ -1208,6 +1212,8 @@ antiAlias Sharp Nítido Font Family & Style Família e Estilo da Fonte Font Family, Style & Size Família, Estilo e Tamanho da Fonte Font List Lista de Fontes + Show Similar Fonts Mostrar Fontes Semelhantes + Clear Similar Fonts Limpar Fontes Semelhantes Font Preview Size Tamanho da Visualização da Fonte Font Size Tamanho da Fonte Variable Font Fonte Variável @@ -2733,6 +2739,8 @@ digits Malayalam Malaiala Search Commands… Pesquisar Comandos… Search commands and tools Pesquisar comandos e ferramentas Search commands and tools… Pesquisar comandos e ferramentas… + Recent Commands Comandos recentes + No recent commands Nenhum comando recente Secondary Secundária Section Symbol Símbolo de Seção Select Selecionar @@ -3936,6 +3944,7 @@ axis Both Ambos @msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado @msg Downloaded {what} {what} baixado @msg Expand Appearance: the selection has a basic appearance Expandir aparência: a seleção tem uma aparência básica +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all alguns efeitos de raster não foram transformados em imagens: ocupariam mais de 1.024 imagens ou 256 megapixels no total @msg Expand: no brush strokes selected Expandir: nenhum traço de pincel selecionado @msg Expand: no gradient fills Expandir: nenhum preenchimento em gradiente @msg Expand: nothing to expand Expandir: nada para expandir @@ -5514,6 +5523,31 @@ axis Both Ambos @msg $.evalFile requires a file path $.evalFile requer um caminho de arquivo @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: o tempo limite deve ser um número finito de milissegundos, 0 ou mais @msg $.evalFile: takes a file path and a timeout $.evalFile: recebe um caminho de arquivo e um tempo limite +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} não está definido +@msg cannot read property '{key}' of {base} não é possível ler a propriedade '{key}' de {base} +@msg cannot set property '{key}' of {base} não é possível gravar a propriedade '{key}' de {base} +@msg cannot read a property of {base} não é possível ler uma propriedade de {base} +@msg cannot set a property of {base} não é possível gravar uma propriedade de {base} +@msg cannot define property '{key}': {why} não é possível definir a propriedade '{key}': {why} +@msg cannot assign to property '{key}': {why} não é possível atribuir à propriedade '{key}': {why} +@msg cannot delete property '{key}' não é possível excluir a propriedade '{key}' +@msg cannot declare function {ident} não é possível declarar a função {ident} +@msg invalid assignment target destino de atribuição inválido +@msg the array's length is read-only o comprimento do array é somente leitura +@msg the property cannot be redefined a propriedade não pode ser redefinida +@msg the object is not extensible o objeto não é extensível +@msg the length cannot be redefined o comprimento não pode ser redefinido +@msg it is read-only ela é somente leitura +@msg an element cannot be deleted um elemento não pode ser excluído +@msg it has only a getter ela tem apenas um getter +@msg the value is a primitive o valor é primitivo @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: linha {line}, coluna {column} de {file}: {e} (lançado) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: linha {line}, coluna {column}: {e} (lançado) @msg {name}: {e} (thrown) {name}: {e} (lançado) @@ -6211,7 +6245,7 @@ mark-style Japanese Japonesas Create Dimension Criar Cota Update Dimensions Atualizar Cotas # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Fecha as extremidades circulares dos perfis abertos. Giros parciais mantêm as faces de corte abertas. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Fecha as extremidades circulares dos perfis abertos. Giros parciais também fecham as faces de corte. @msg span must be "object" or "selection", got {v} span deve ser "object" ou "selection", não {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" posiciona um `gradient`, não uma amostra @msg span: "selection" places a gradient: give `gradient` span: "selection" posiciona um degradê: informe `gradient` @@ -6394,6 +6428,7 @@ mark-style Japanese Japonesas Single Word Justification: Justificação de Palavra Única: Full Justify Justificação Completa Minimum must not exceed Desired, nor Desired Maximum. O mínimo não pode passar do desejado, nem o desejado do máximo. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: o mínimo não pode passar do desejado, nem o desejado do máximo Justification Justificação Add filters from the list above Adicione filtros da lista acima Add to Stack Adicionar à Pilha @@ -7450,6 +7485,24 @@ breakText Glyphs Glifos # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir traços em demarcadores @msg select paths with dashed strokes to expand selecione demarcadores com traçado tracejado para expandir +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Círculo tangente… + Tangent Circle Círculo tangente + Circle: Círculo: +@msg `ids` names an object twice `ids` indica um objeto duas vezes +@msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos +@msg `radius` must be from 0.01 to 1000000 pt `radius` deve ser de 0.01 a 1000000 pt +@msg two shapes need a `radius` duas formas precisam de um `radius` +@msg three shapes set the radius themselves: leave `radius` out três formas definem o raio sozinhas: omita `radius` +@msg `circle` must be from 0 to 64 `circle` deve ser de 0 a 64 +@msg a shape has no outline uma forma não tem contorno +@msg the shapes are too complex: at most 2000 segments in all as formas são complexas demais: no máximo 2000 segmentos no total +@msg these shapes take too long to search a busca demora demais para estas formas +@msg more than 64 circles touch these shapes: they may touch along a whole curve mais de 64 círculos tocam estas formas: eles podem tocá-las ao longo de uma curva inteira +@msg no circle touches these shapes nenhum círculo toca estas formas +@msg `circle` is past the last circle found ({found}) `circle` passa do último círculo encontrado ({found}) +@msg object {value} is not a path or compound path o objeto {value} não é um caminho nem um caminho composto +@msg these shapes are too small to measure estas formas são pequenas demais para medir # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Ferramentas de Documento Save a Timestamped Copy Salvar uma Cópia com Data e Hora @@ -7504,7 +7557,7 @@ breakText Glyphs Glifos @msg stroke cannot be set on a symbol instance stroke não pode ser definido em uma instância de símbolo @msg fill on a symbol instance must be a solid color or none o fill de uma instância de símbolo deve ser uma cor sólida ou none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} não pode ser definido em uma imagem sem o efeito Converter em Forma ou Contornar Objeto -@msg pass newName, registration, exportType, nineSlice and/or type informe newName, registration, exportType, nineSlice e/ou type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid informe newName, registration, exportType, nineSlice, type e/ou alignToPixelGrid # Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). on the canvas to create one na tela para criar um 1 Layer 1 camada @@ -9129,7 +9182,9 @@ swatch Yellow Green Verde-amarelado @msg position must be normal, superscript or subscript position deve ser normal, superscript ou subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position deve ser topLeft, topRight, bottomLeft ou bottomRight @msg positions must be between 0 and 100000 pt positions deve estar entre 0 e 100000 pt +@msg ppi can't be more than {max} for this image ppi não pode ser maior que {max} para esta imagem @msg ppi must be a positive number, not {ppi} ppi deve ser um número positivo, não {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim mantém os pixels da imagem como estão: omita ppi @msg ppi must be between 1 and 2400 ppi deve estar entre 1 e 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` não é transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape deve ser clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 4bad630382..b6cf55f6ce 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1034,6 +1034,10 @@ font-technology Variable Вариативные Em Box Кегельная площадка x-Height Высота строчных ICF Box Рамка ICF + Show Sample Показать образец + Hide Sample Скрыть образец + Max Ascent/Descent Макс. высота/глубина + Max Ascender Макс. выносной элемент вверх Em Dash Длинное тире Em Space Круглая шпация Embed Внедрить @@ -1359,6 +1363,8 @@ file-filter Templates Шаблоны Font Family & Style Семейство и стиль шрифта Font Family, Style & Size Семейство, стиль и размер шрифта Font List Список шрифтов + Show Similar Fonts Показать похожие шрифты + Clear Similar Fonts Сбросить похожие шрифты Font Preview Size Размер предварительного просмотра шрифта Font Size Размер шрифта Variable Font Вариативный шрифт @@ -3306,6 +3312,8 @@ digits Malayalam Малаялам @msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1} Search commands and tools Поиск команд и инструментов Search commands and tools… Поиск команд и инструментов… + Recent Commands Недавние команды + No recent commands Нет недавних команд Search Commands… Поиск команд… Secondary Вторичный Section Symbol Символ параграфа @@ -4503,6 +4511,31 @@ axis Both Оба @msg $.evalFile requires a file path $.evalFile требует путь к файлу @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: тайм-аут должен быть конечным числом миллисекунд, 0 или больше @msg $.evalFile: takes a file path and a timeout $.evalFile: принимает путь к файлу и тайм-аут +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} не определено +@msg cannot read property '{key}' of {base} невозможно прочитать свойство '{key}' у {base} +@msg cannot set property '{key}' of {base} невозможно задать свойство '{key}' у {base} +@msg cannot read a property of {base} невозможно прочитать свойство у {base} +@msg cannot set a property of {base} невозможно задать свойство у {base} +@msg cannot define property '{key}': {why} невозможно определить свойство '{key}': {why} +@msg cannot assign to property '{key}': {why} невозможно присвоить значение свойству '{key}': {why} +@msg cannot delete property '{key}' невозможно удалить свойство '{key}' +@msg cannot declare function {ident} невозможно объявить функцию {ident} +@msg invalid assignment target недопустимая цель присваивания +@msg the array's length is read-only длина массива доступна только для чтения +@msg the property cannot be redefined свойство нельзя переопределить +@msg the object is not extensible объект нерасширяем +@msg the length cannot be redefined длину нельзя переопределить +@msg it is read-only оно доступно только для чтения +@msg an element cannot be deleted элемент нельзя удалить +@msg it has only a getter у него есть только геттер +@msg the value is a primitive значение примитивное @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: строка {line}, столбец {column} в {file}: {e} (исключение) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: строка {line}, столбец {column}: {e} (исключение) @msg {name}: {e} (thrown) {name}: {e} (исключение) @@ -4619,6 +4652,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур @msg Downloaded {what} Скачано: {what} @msg Expand Appearance: the selection has a basic appearance Разбор оформления: у выделения основное оформление +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all некоторые растровые эффекты не преобразованы в изображения: для них нужно больше 1024 изображений или 256 мегапикселей в сумме @msg Expand: no brush strokes selected Разбор: не выделены мазки кисти @msg Expand: no gradient fills Разбор: нет градиентных заливок @msg Expand: nothing to expand Разбор: нечего разбирать @@ -5946,7 +5980,7 @@ lighting Light Свет @msg Unknown dimension style Неизвестный стиль размера @msg Unknown unit Неизвестная единица # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Закрывает круглые торцы открытых профилей. При неполном вращении боковые срезы остаются открытыми. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Закрывает круглые торцы открытых профилей. При неполном вращении боковые срезы тоже закрываются. Distance Расстояние @msg span must be "object" or "selection", got {v} span должен быть "object" или "selection", а не {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" размещает `gradient`, а не образец @@ -6100,6 +6134,7 @@ lighting Light Свет Single Word Justification: Выключка одного слова: Full Justify Полная выключка Minimum must not exceed Desired, nor Desired Maximum. Минимум не может превышать желательное значение, а желательное — максимум. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: минимум не может превышать желательное значение, а желательное — максимум Minimum Минимум Justification Выключка Add filters from the list above Добавьте фильтры из списка выше @@ -7409,6 +7444,24 @@ breakText Glyphs Глифы # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разобрать штрихи на контуры @msg select paths with dashed strokes to expand выделите контуры со штриховой обводкой для разбора +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Касательная окружность… + Tangent Circle Касательная окружность + Circle: Окружность: +@msg `ids` names an object twice `ids` указывает объект дважды +@msg select two or three paths or compound paths выделите два или три контура или составных контура +@msg `radius` must be from 0.01 to 1000000 pt `radius` должен быть от 0.01 до 1000000 pt +@msg two shapes need a `radius` для двух фигур нужен `radius` +@msg three shapes set the radius themselves: leave `radius` out три фигуры сами задают радиус: не указывайте `radius` +@msg `circle` must be from 0 to 64 `circle` должен быть от 0 до 64 +@msg a shape has no outline у фигуры нет контура +@msg the shapes are too complex: at most 2000 segments in all фигуры слишком сложные: всего не более 2000 сегментов +@msg these shapes take too long to search поиск для этих фигур занимает слишком много времени +@msg more than 64 circles touch these shapes: they may touch along a whole curve этих фигур касается больше 64 окружностей: возможно, они касаются вдоль целой кривой +@msg no circle touches these shapes ни одна окружность не касается этих фигур +@msg `circle` is past the last circle found ({found}) `circle` больше числа найденных окружностей ({found}) +@msg object {value} is not a path or compound path объект {value} не является контуром или составным контуром +@msg these shapes are too small to measure эти фигуры слишком малы для измерения # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Инструменты документа Save a Timestamped Copy Сохранить копию с датой и временем @@ -7463,7 +7516,7 @@ breakText Glyphs Глифы @msg stroke cannot be set on a symbol instance stroke нельзя задать для экземпляра символа @msg fill on a symbol instance must be a solid color or none fill экземпляра символа должен быть сплошным цветом или none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} нельзя задать для изображения без эффекта «Преобразовать в фигуру» или «Обвести объект» -@msg pass newName, registration, exportType, nineSlice and/or type укажите newName, registration, exportType, nineSlice и/или type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid укажите newName, registration, exportType, nineSlice, type и/или alignToPixelGrid Text Flow Поток текста By Rows По строкам By Columns По столбцам diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 45bed1da83..7c0877a9fa 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1306,6 +1306,8 @@ font-technology Variable Variabla Font Family & Style Typsnittsfamilj och stil Font Family, Style & Size Typsnittsfamilj, stil och storlek Font List Typsnittslista + Show Similar Fonts Visa liknande typsnitt + Clear Similar Fonts Rensa liknande typsnitt Font Preview Size Storlek på typsnittsförhandsgranskning Font Size Teckenstorlek Variable Font Variabelt typsnitt @@ -3196,6 +3198,8 @@ digits Malayalam Malayalam Search All Sök i alla Search commands and tools Sök kommandon och verktyg Search commands and tools… Sök kommandon och verktyg… + Recent Commands Senaste kommandon + No recent commands Inga senaste kommandon Search Commands… Sök kommandon… Secondary Sekundär Section Symbol Paragraftecken @@ -4376,6 +4380,44 @@ axis Both Båda @msg $.evalFile requires a file path $.evalFile kräver en filsökväg @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: tidsgränsen måste vara ett ändligt antal millisekunder, 0 eller mer @msg $.evalFile: takes a file path and a timeout $.evalFile: tar en filsökväg och en tidsgräns +@msg assignment to a constant binding tilldelning till en konstant bindning +@msg invalid array length ogiltig arraylängd +@msg array literal too long arrayliteralen är för lång +@msg the value is not a function värdet är inte en funktion +@msg apply was called on a value that is not a function apply anropades på ett värde som inte är en funktion +@msg the argument list is not an object argumentlistan är inte ett objekt +@msg too many arguments för många argument +@msg the value is not a constructor värdet är inte en konstruktor +@msg cannot convert the object to a primitive value objektet kan inte konverteras till ett primitivt värde +@msg cannot convert undefined or null to an object undefined eller null kan inte konverteras till ett objekt +@msg the right side of 'in' is not an object högersidan av 'in' är inte ett objekt +@msg the right side of 'instanceof' is not a function högersidan av 'instanceof' är inte en funktion +@msg the function's prototype is not an object funktionens prototyp är inte ett objekt +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} är inte definierat +@msg cannot read property '{key}' of {base} det går inte att läsa egenskapen '{key}' för {base} +@msg cannot set property '{key}' of {base} det går inte att sätta egenskapen '{key}' för {base} +@msg cannot read a property of {base} det går inte att läsa en egenskap för {base} +@msg cannot set a property of {base} det går inte att sätta en egenskap för {base} +@msg cannot define property '{key}': {why} det går inte att definiera egenskapen '{key}': {why} +@msg cannot assign to property '{key}': {why} det går inte att tilldela egenskapen '{key}': {why} +@msg cannot delete property '{key}' det går inte att ta bort egenskapen '{key}' +@msg cannot declare function {ident} det går inte att deklarera funktionen {ident} +@msg invalid assignment target ogiltigt tilldelningsmål +@msg the array's length is read-only arrayens längd är skrivskyddad +@msg the property cannot be redefined egenskapen kan inte definieras om +@msg the object is not extensible objektet kan inte utökas +@msg the length cannot be redefined längden kan inte definieras om +@msg it is read-only den är skrivskyddad +@msg an element cannot be deleted ett element kan inte tas bort +@msg it has only a getter den har bara en getter +@msg the value is a primitive värdet är primitivt @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: rad {line}, kolumn {column} i {file}: {e} (kastat) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: rad {line}, kolumn {column}: {e} (kastat) @msg {name}: {e} (thrown) {name}: {e} (kastat) @@ -4492,6 +4534,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana @msg Downloaded {what} Hämtade {what} @msg Expand Appearance: the selection has a basic appearance Expandera utseende: markeringen har ett grundläggande utseende +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all vissa rastereffekter gjordes inte om till bilder: de skulle kräva mer än 1 024 bilder eller totalt 256 megapixlar @msg Expand: no brush strokes selected Expandera: inga penseldrag är markerade @msg Expand: no gradient fills Expandera: inga gradientfyllningar @msg Expand: nothing to expand Expandera: ingenting att expandera @@ -5309,6 +5352,10 @@ liquify-list-end {0}, {1} {0} och {1} Em Box Em-ruta x-Height x-höjd ICF Box ICF-ruta + Show Sample Visa exempel + Hide Sample Dölj exempel + Max Ascent/Descent Max höjd/djup + Max Ascender Max uppstapel @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` är stegreferensen {r}, som bara `run` och `command_batch` löser upp @msg `ids` must be an array of object ids, not {v} `ids` måste vara en array med objekt-id:n, inte {v} @msg `colors` must be an array of colors, not {v} `colors` måste vara en array med färger, inte {v} @@ -6190,7 +6237,7 @@ theme Appearance Utseende By Object Efter objekt Check an artboard to save. Markera en rityta som ska sparas. Clear All Rensa alla - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Stäng de cirkulära ändarna på öppna profiler. Partiella svep behåller sina snittsidor öppna. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Stäng de cirkulära ändarna på öppna profiler. Partiella svep stänger även sina snittsidor. Color Panel Options Alternativ för panelen Färg Color blindness – Tritanopia-type Färgblindhet – tritanopi Create Dimension Skapa mått @@ -7435,6 +7482,24 @@ breakText Glyphs Glyfer # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandera streck till banor @msg select paths with dashed strokes to expand markera banor med streckad kontur att expandera +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Tangentcirkel… + Tangent Circle Tangentcirkel + Circle: Cirkel: +@msg `ids` names an object twice `ids` anger ett objekt två gånger +@msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor +@msg `radius` must be from 0.01 to 1000000 pt `radius` måste vara från 0.01 till 1000000 pt +@msg two shapes need a `radius` två former kräver en `radius` +@msg three shapes set the radius themselves: leave `radius` out tre former bestämmer radien själva: utelämna `radius` +@msg `circle` must be from 0 to 64 `circle` måste vara från 0 till 64 +@msg a shape has no outline en form har ingen kontur +@msg the shapes are too complex: at most 2000 segments in all formerna är för komplexa: högst 2000 segment totalt +@msg these shapes take too long to search sökningen tar för lång tid för formerna +@msg more than 64 circles touch these shapes: they may touch along a whole curve fler än 64 cirklar rör vid formerna: de kan röra vid dem längs en hel kurva +@msg no circle touches these shapes ingen cirkel rör vid formerna +@msg `circle` is past the last circle found ({found}) `circle` ligger efter den sista funna cirkeln ({found}) +@msg object {value} is not a path or compound path objekt {value} är inte en bana eller sammansatt bana +@msg these shapes are too small to measure formerna är för små för att mätas # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Dokumentverktyg Save a Timestamped Copy Spara en kopia med tidsstämpel @@ -7489,7 +7554,7 @@ breakText Glyphs Glyfer @msg stroke cannot be set on a symbol instance stroke kan inte anges för en symbolinstans @msg fill on a symbol instance must be a solid color or none fill för en symbolinstans måste vara en enfärgad färg eller none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} kan inte anges för en bild utan effekten Konvertera till form eller Konvertera objekt till konturer -@msg pass newName, registration, exportType, nineSlice and/or type ange newName, registration, exportType, nineSlice och/eller type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid ange newName, registration, exportType, nineSlice, type och/eller alignToPixelGrid Text Flow Textflöde By Rows Radvis By Columns Kolumnvis @@ -8642,7 +8707,9 @@ digits Hindi Hindi @msg position must be normal, superscript or subscript position måste vara normal, superscript eller subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position måste vara topLeft, topRight, bottomLeft eller bottomRight @msg positions must be between 0 and 100000 pt positionerna måste vara mellan 0 och 100 000 pt +@msg ppi can't be more than {max} for this image ppi kan inte vara mer än {max} för den här bilden @msg ppi must be a positive number, not {ppi} ppi måste vara ett positivt tal, inte {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim behåller bildens pixlar som de är: utelämna ppi @msg ppi must be between 1 and 2400 ppi måste vara mellan 1 och 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` är inte transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape måste vara clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 09f4b2adf8..2a307e0b4d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2194,6 +2194,22 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// The error that `text.setFormat` and the paragraph style commands give when a justification +/// setting's Minimum, Desired and Maximum are out of order is translated in every +/// complete-message language, with the setting's name kept. +#[test] +fn justification_order_error_translates_with_the_setting_name() { + for name in ["wordSpacing", "justification.glyph_scaling"] { + let error = format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &error); + assert!(shown != error && !shown.contains("Desired"), "{code}: {shown}"); + assert!(shown.contains(&format!("`{name}`")), "{code}: {shown}"); + } + } +} + /// A script's error about unused `answers` and Liquify's note on the objects it left as they were /// are translated whole for one object as well as for several, in every complete-message language, /// and keep their counts. @@ -3296,12 +3312,23 @@ fn f(i: &mut Interp, interp: &mut Interp) -> JsResult { let _ = self.error("the path has an empty step"); let _ = self.throw_host(t, "not an error: a longer name"); let _ = throw_type_error(interp, "not an error: a function"); + let _ = self.reject_bool(throw, &k, "the object is not extensible"); + let _ = self.reject(throw, &key("length"), "it is read-only"); Ok(Value::Undefined) } "#; let js: Vec<_> = ERROR_HELPERS.iter().filter(|(c, _, _)| *c == "js").map(|&(_, call, before)| (call, before)).collect(); let found = source_messages(code, &js, &Default::default()); - assert_eq!(found, ["{what}: the object is not a File or a Folder", "File.seek: the mode must be 0, 1 or 2", "the path has an empty step"]); + assert_eq!( + found, + [ + "{what}: the object is not a File or a Folder", + "File.seek: the mode must be 0, 1 or 2", + "the path has an empty step", + "the object is not extensible", + "it is read-only" + ] + ); } /// The scan reads the message a `.map_err` closure returns, a literal, a `format!` string or a @@ -3810,6 +3837,128 @@ fn script_host_errors_are_translated() { } } +/// The errors the script interpreter's core throws at a script (an unknown name, a property of +/// `null` or `undefined`, a property that cannot be defined, assigned or deleted and why, a value +/// that is not a function or a constructor) are translated in every language of +/// [`COMPLETE_MESSAGES`], on their own and in the status bar's line for a run that ends with one. +/// Names, property names, `null`, `undefined` and the operators `in` and `instanceof` stay as they +/// are, and a script that catches one reads its English message. +#[test] +fn script_interpreter_core_errors_are_translated() { + use serde_json::json; + let scanned = message_literals(); + let templates = [ + "assignment to a constant binding", + "invalid array length", + "array literal too long", + "the value is not a function", + "apply was called on a value that is not a function", + "the argument list is not an object", + "too many arguments", + "the value is not a constructor", + "cannot convert the object to a primitive value", + "cannot convert undefined or null to an object", + "the right side of 'in' is not an object", + "the right side of 'instanceof' is not a function", + "the function's prototype is not an object", + "{ident} is not defined", + "cannot read property '{key}' of {base}", + "cannot set property '{key}' of {base}", + "cannot read a property of {base}", + "cannot set a property of {base}", + "cannot define property '{key}': {why}", + "cannot assign to property '{key}': {why}", + "cannot delete property '{key}'", + "cannot declare function {ident}", + "the array's length is read-only", + "the property cannot be redefined", + "the object is not extensible", + "the length cannot be redefined", + "it is read-only", + "an element cannot be deleted", + "it has only a getter", + "the value is a primitive", + ]; + for template in templates { + assert!(scanned.contains(template), "{template}"); + } + // The compiler gives this one to the interpreter as the text of the error it throws. + let compiler = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../js/src/compiler.rs"); + assert!(std::fs::read_to_string(compiler).unwrap_or_default().contains("\"invalid assignment target\"")); + let mut s = vectorcraft_engine::Session::new(); + let mut lines: Vec<(String, String, Vec<&str>)> = vec![]; + for (source, inner, kept) in [ + ("nope", "nope is not defined", vec!["nope"]), + // An identifier that is also a message with its own entry stays as written. + ("damaged", "damaged is not defined", vec!["damaged"]), + ("null.x", "cannot read property 'x' of null", vec!["'x'", "null"]), + ("var u; u['y'] = 1", "cannot set property 'y' of undefined", vec!["'y'", "undefined"]), + ("var u; u.y = 1", "cannot set a property of undefined", vec!["undefined"]), + ("null[new Array(300).join('a')]", "cannot read a property of null", vec!["null"]), + ("null['']", "cannot read property '' of null", vec!["''", "null"]), + ("null['invalid array length']", "cannot read property 'invalid array length' of null", vec!["'invalid array length'", "null"]), + ( + "'use strict'; var o = {}; Object.defineProperty(o, 'a', {value: 1}); o.a = 2", + "cannot assign to property 'a': it is read-only", + vec!["'a'"], + ), + // A property named like the reason: the name stays as written, and the reason is translated. + ( + "'use strict'; var o = {}; Object.defineProperty(o, 'it is read-only', {value: 1}); o['it is read-only'] = 2", + "cannot assign to property 'it is read-only': it is read-only", + vec!["'it is read-only'"], + ), + ( + "'use strict'; var o = {}; Object.defineProperty(o, 'g', {get: function () { return 1; }}); o.g = 2", + "cannot assign to property 'g': it has only a getter", + vec!["'g'"], + ), + ("'use strict'; var o = Object.preventExtensions({}); o.b = 1", "cannot assign to property 'b': the object is not extensible", vec!["'b'"]), + ( + "Object.defineProperty(Object.preventExtensions({}), 'c', {value: 1})", + "cannot define property 'c': the object is not extensible", + vec!["'c'"], + ), + ( + "var o = {}; Object.defineProperty(o, 'd', {value: 1}); Object.defineProperty(o, 'd', {value: 2})", + "cannot define property 'd': the property cannot be redefined", + vec!["'d'"], + ), + ("'use strict'; delete Object.prototype", "cannot delete property 'prototype'", vec!["'prototype'"]), + ("'use strict'; 'abc'.x = 1", "cannot assign to property 'x': the value is a primitive", vec!["'x'"]), + ("(function f() { 'use strict'; f = 1; })()", "assignment to a constant binding", vec![]), + ("new Array(-1)", "invalid array length", vec![]), + ("var n = 1; n()", "the value is not a function", vec![]), + ("new 1", "the value is not a constructor", vec![]), + ("'a' in 1", "the right side of 'in' is not an object", vec!["'in'"]), + ("1 instanceof 1", "the right side of 'instanceof' is not a function", vec!["'instanceof'"]), + ("function f() {} for (f() in {a: 1}) {}", "invalid assignment target", vec![]), + ] { + let e = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_err().to_string(); + assert!(e.starts_with("t.js: ") && e.contains(&format!("Error: {inner} (")), "{source}: {e}"); + lines.push((e, inner.to_string(), kept)); + } + // A script that catches one of these errors reads it in English, whatever the interface's language. + let caught = "try { nope; } catch (e) { if (e.message !== 'nope is not defined') throw new Error(e.message); }"; + assert!(s.execute("script.run", &json!({"source": caught, "name": "t.js"})).is_ok()); + let reasons = &templates[22..]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for m in templates[..13].iter().chain(reasons).chain(["invalid assignment target"].iter()) { + assert_ne!(message(lang, m), *m, "{code}"); + } + for (line, inner, kept) in &lines { + let shown = message(lang, inner); + assert_ne!(shown, *inner, "{code}"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {inner} -> {shown}"); + assert!(reasons.iter().all(|r| !inner.ends_with(r) || shown.ends_with(&message(lang, r))), "{code}: {inner} -> {shown}"); + let whole = message(lang, line); + let kinds = ["(thrown)", "(limit)", "(syntax)", "(stopped)", "(internal)"]; + assert!(whole.starts_with("t.js") && whole.contains(&shown) && kinds.iter().all(|k| !whole.contains(k)), "{code}: {line} -> {whole}"); + } + } +} + /// A manifest whose `commands` value has the wrong shape is refused with an error that every /// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the /// manifest included. @@ -5069,9 +5218,10 @@ const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Oth /// value), `out_err(at, msg)` (plug-in output), `in_range(x, lo, hi, at, what)` and /// `unit(x, at, what)` (a painted effect's numbers) and `.read_packed(packed, what, max)` (the block /// a plug-in returned), and the script interpreter's methods that throw an error at a script: -/// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`. A helper that -/// starts with `.` is a method of any receiver; any other is a function, not a type's own function -/// of the same name (`Grays::param(C, p)`). +/// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`, with the reasons +/// it gives for a property it cannot define or assign (`.reject_bool(throw, key, why)` and +/// `.reject(throw, key, why)`). A helper that starts with `.` is a method of any receiver; any other +/// is a function, not a type's own function of the same name (`Grays::param(C, p)`). const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("engine", "bad(", 1), ("engine", "err(", 0), @@ -5091,6 +5241,8 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("js", ".type_error(", 0), ("js", ".throw(", 1), ("js", ".error(", 0), + ("js", ".reject_bool(", 2), + ("js", ".reject(", 2), ]; /// Error variants whose first argument is a name, not a message: a command id diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b1c979da76..0d6cd69ad1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1302,6 +1302,8 @@ font-technology Variable Değişken Font Family & Style Yazı Tipi Ailesi ve Stili Font Family, Style & Size Yazı Tipi Ailesi, Stili ve Boyutu Font List Yazı Tipi Listesi + Show Similar Fonts Benzer Yazı Tiplerini Göster + Clear Similar Fonts Benzer Yazı Tiplerini Temizle Font Preview Size Yazı Tipi Önizleme Boyutu Font Size Yazı Tipi Boyutu Font: Yazı tipi: @@ -3054,6 +3056,7 @@ digits Malayalam Malayalam Letter Spacing: Harf Boşluğu: Lights Işıklar Minimum must not exceed Desired, nor Desired Maximum. Minimum, İstenen'i; İstenen ise Maksimum'u aşmamalıdır. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum, İstenen'i; İstenen ise Maksimum'u aşmamalıdır Select by Color Renge Göre Seç Set History Limit… Geçmiş Sınırını Ayarla… Single Word Justification: Tek Sözcük Yaslama: @@ -3067,6 +3070,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` şu adlardan oluşan bir dizi olmalıdır: {_1} Search commands and tools Komutları ve araçları arayın Search commands and tools… Komutları ve araçları arayın… + Recent Commands Son komutlar + No recent commands Son komut yok Search Commands… Arama Komutları… Secondary İkincil Section Symbol Bölüm Sembolü @@ -4231,6 +4236,31 @@ axis Both Her İkisi @msg $.evalFile requires a file path $.evalFile bir dosya yolu gerektirir @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: zaman aşımı sonlu bir milisaniye sayısı olmalıdır, 0 veya daha fazla @msg $.evalFile: takes a file path and a timeout $.evalFile: bir dosya yolu ve bir zaman aşımı alır +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} tanımlı değil +@msg cannot read property '{key}' of {base} {base} değerinin '{key}' özelliği okunamıyor +@msg cannot set property '{key}' of {base} {base} değerinin '{key}' özelliği ayarlanamıyor +@msg cannot read a property of {base} {base} değerinin bir özelliği okunamıyor +@msg cannot set a property of {base} {base} değerinin bir özelliği ayarlanamıyor +@msg cannot define property '{key}': {why} '{key}' özelliği tanımlanamıyor: {why} +@msg cannot assign to property '{key}': {why} '{key}' özelliğine atama yapılamıyor: {why} +@msg cannot delete property '{key}' '{key}' özelliği silinemiyor +@msg cannot declare function {ident} {ident} işlevi bildirilemiyor +@msg invalid assignment target geçersiz atama hedefi +@msg the array's length is read-only dizinin uzunluğu salt okunur +@msg the property cannot be redefined özellik yeniden tanımlanamaz +@msg the object is not extensible nesne genişletilemez +@msg the length cannot be redefined uzunluk yeniden tanımlanamaz +@msg it is read-only salt okunur +@msg an element cannot be deleted bir öğe silinemez +@msg it has only a getter yalnızca getter'ı var +@msg the value is a primitive değer ilkel @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, satır {line}, sütun {column}: {e} (fırlatıldı) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: satır {line}, sütun {column}: {e} (fırlatıldı) @msg {name}: {e} (thrown) {name}: {e} (fırlatıldı) @@ -4337,6 +4367,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin @msg Downloaded {what} {what} indirildi @msg Expand Appearance: the selection has a basic appearance Görünümü Genişlet: seçimin temel bir görünümü vardır +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all bazı raster efektleri görüntüye dönüştürülmedi: toplamda 1.024'ten fazla görüntü veya 256 megapiksel gerektirirlerdi @msg Expand: no brush strokes selected Genişlet: seçili fırça darbesi yok @msg Expand: no gradient fills Genişlet: degrade dolgu yok @msg Expand: nothing to expand Genişlet: genişletilecek bir şey yok @@ -5150,6 +5181,10 @@ liquify-list-end {0}, {1} {0} ve {1} Em Box Em Kutusu x-Height x-Yüksekliği ICF Box ICF Kutusu + Show Sample Örneği Göster + Hide Sample Örneği Gizle + Max Ascent/Descent Maks. Yükseklik/Derinlik + Max Ascender Maks. Yükselen @msg `colors` must be an array of colors, not {v} `colors` {v} değil, bir renk dizisi olmalıdır @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id`, yalnızca `run` ve `command_batch` komutlarının çözümlediği {r} adım referansıdır @msg `ids` must be an array of object ids, not {v} `ids` bir nesne kimlikleri dizisi olmalıdır, {v} değil @@ -6084,7 +6119,7 @@ theme Appearance Görünüm @msg Unknown dimension orientation Bilinmeyen boyut yönü @msg Unknown dimension style Bilinmeyen boyut stili @msg Unknown unit Bilinmeyen birim - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını açık tutar. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Açık profillerin dairesel uçlarını kapatın. Kısmi süpürmeler kesik taraflarını da kapatır. @msg span must be "object" or "selection", got {v} span "object" veya "selection" olmalıdır, {v} değil @msg span: "selection" places a `gradient`, not a swatch span: "selection" bir renk örneği değil, bir `gradient` yerleştirir @msg span: "selection" places a gradient: give `gradient` span: "selection" bir degrade yerleştirir: `gradient` verin @@ -8280,7 +8315,9 @@ axis Y Axis Y ekseni @msg position must be normal, superscript or subscript position normal, superscript veya subscript olmalıdır @msg position must be topLeft, topRight, bottomLeft or bottomRight position topLeft, topRight, bottomLeft veya bottomRight olmalıdır @msg positions must be between 0 and 100000 pt konumlar 0 ile 100000 pt arasında olmalıdır +@msg ppi can't be more than {max} for this image bu görüntü için ppi {max} değerinden büyük olamaz @msg ppi must be a positive number, not {ppi} ppi pozitif bir sayı olmalıdır, {ppi} değil +@msg trim keeps the image's pixels as they are: leave out ppi trim görüntünün piksellerini olduğu gibi korur: ppi belirtmeyin @msg ppi must be between 1 and 2400 ppi 1 ile 2400 arasında olmalıdır @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill değerlerinden biri değil @msg preserveShape must be clippingMask|transparency preserveShape clippingMask|transparency olmalıdır @@ -9297,6 +9334,24 @@ breakText Glyphs Glifler # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Tireleri Yollara Genişlet @msg select paths with dashed strokes to expand genişletilecek kesikli konturlu yolları seçin +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Teğet Daire… + Tangent Circle Teğet Daire + Circle: Daire: +@msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor +@msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin +@msg `radius` must be from 0.01 to 1000000 pt `radius` 0.01 ile 1000000 pt arasında olmalıdır +@msg two shapes need a `radius` iki şekil için `radius` gerekir +@msg three shapes set the radius themselves: leave `radius` out üç şekil yarıçapı kendisi belirler: `radius` değerini vermeyin +@msg `circle` must be from 0 to 64 `circle` 0 ile 64 arasında olmalıdır +@msg a shape has no outline bir şeklin anahattı yok +@msg the shapes are too complex: at most 2000 segments in all şekiller çok karmaşık: toplamda en fazla 2000 bölüm +@msg these shapes take too long to search bu şekiller için arama çok uzun sürüyor +@msg more than 64 circles touch these shapes: they may touch along a whole curve bu şekillere 64'ten fazla daire değiyor: bütün bir eğri boyunca değiyor olabilirler +@msg no circle touches these shapes bu şekillere hiçbir daire değmiyor +@msg `circle` is past the last circle found ({found}) `circle` bulunan son dairenin ötesinde ({found}) +@msg object {value} is not a path or compound path {value} nesnesi bir yol veya bileşik yol değil +@msg these shapes are too small to measure bu şekiller ölçülemeyecek kadar küçük # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Belge Araçları Save a Timestamped Copy Zaman Damgalı Bir Kopya Kaydet @@ -9351,7 +9406,7 @@ breakText Glyphs Glifler @msg stroke cannot be set on a symbol instance stroke bir sembol örneğinde ayarlanamaz @msg fill on a symbol instance must be a solid color or none bir sembol örneğinin fill değeri düz renk veya none olmalıdır @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key}, Şekle Dönüştür veya Anahat Nesnesi efekti olmayan bir görüntüde ayarlanamaz -@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice ve/veya type verin +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid newName, registration, exportType, nineSlice, type ve/veya alignToPixelGrid verin Text Flow Metin Akışı By Rows Satırlara Göre By Columns Sütunlara Göre diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 37edfbbdeb..df83bd9dc8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1039,6 +1039,10 @@ font-technology Variable Варіативні Cap Height Висота великих літер x-Height Висота малих літер ICF Box Рамка ICF + Show Sample Показати зразок + Hide Sample Приховати зразок + Max Ascent/Descent Макс. висота/глибина + Max Ascender Макс. виносний елемент вгору Em Dash Довге тире Em Space Кругла шпація Embed Вбудувати @@ -1362,6 +1366,8 @@ file-filter Templates Шаблони Font Family & Style Сімейство та стиль шрифту Font Family, Style & Size Сімейство, стиль та розмір шрифту Font List Список шрифтів + Show Similar Fonts Показати схожі шрифти + Clear Similar Fonts Скинути схожі шрифти Font Preview Size Розмір попереднього перегляду шрифту Font Size Розмір шрифту Variable Font Варіативний шрифт @@ -3309,6 +3315,8 @@ digits Malayalam Малаялам @msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1} Search commands and tools Пошук команд та інструментів Search commands and tools… Пошук команд та інструментів… + Recent Commands Нещодавні команди + No recent commands Немає нещодавніх команд Search Commands… Пошук команд… Secondary Вторинний Section Symbol Символ параграфа @@ -4502,6 +4510,31 @@ axis Both Обидві @msg $.evalFile requires a file path $.evalFile потребує шляху до файлу @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: тайм-аут має бути скінченним числом мілісекунд, 0 або більше @msg $.evalFile: takes a file path and a timeout $.evalFile: приймає шлях до файлу і тайм-аут +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} не визначено +@msg cannot read property '{key}' of {base} неможливо прочитати властивість '{key}' у {base} +@msg cannot set property '{key}' of {base} неможливо встановити властивість '{key}' у {base} +@msg cannot read a property of {base} неможливо прочитати властивість у {base} +@msg cannot set a property of {base} неможливо встановити властивість у {base} +@msg cannot define property '{key}': {why} неможливо визначити властивість '{key}': {why} +@msg cannot assign to property '{key}': {why} неможливо присвоїти значення властивості '{key}': {why} +@msg cannot delete property '{key}' неможливо видалити властивість '{key}' +@msg cannot declare function {ident} неможливо оголосити функцію {ident} +@msg invalid assignment target недійсна ціль присвоєння +@msg the array's length is read-only довжина масиву доступна лише для читання +@msg the property cannot be redefined властивість не можна перевизначити +@msg the object is not extensible об'єкт не можна розширювати +@msg the length cannot be redefined довжину не можна перевизначити +@msg it is read-only вона доступна лише для читання +@msg an element cannot be deleted елемент не можна видалити +@msg it has only a getter вона має лише гетер +@msg the value is a primitive значення примітивне @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: рядок {line}, стовпець {column} у {file}: {e} (виняток) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: рядок {line}, стовпець {column}: {e} (виняток) @msg {name}: {e} (thrown) {name}: {e} (виняток) @@ -4607,6 +4640,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур @msg Downloaded {what} Завантажено: {what} @msg Expand Appearance: the selection has a basic appearance Розбір оформлення: виділення основне оформлення +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all деякі растрові ефекти не перетворено на зображення: для них потрібно понад 1024 зображення або загалом 256 мегапікселів @msg Expand: no brush strokes selected Розбір: не виділено мазки пензлі @msg Expand: no gradient fills Розбір: немає градієнтних заливок @msg Expand: nothing to expand Розбір: нема чого розбирати @@ -5928,7 +5962,7 @@ lighting Light Світло @msg Unknown dimension style Невідомий стиль розміру @msg Unknown unit Невідома одиниця # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Закриває круглі торці відкритих профілів. За неповного обертання бічні зрізи залишаються відкритими. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Закриває круглі торці відкритих профілів. За неповного обертання бічні зрізи теж закриваються. Distance Відстань @msg span must be "object" or "selection", got {v} span має бути "object" або "selection", а не {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" розміщує `gradient`, а не зразок @@ -6082,6 +6116,7 @@ lighting Light Світло Single Word Justification: Вирівнювання одного слова: Full Justify Повне вирівнювання Minimum must not exceed Desired, nor Desired Maximum. Мінімум не може перевищувати бажане значення, а бажане — максимум. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: мінімум не може перевищувати бажане значення, а бажане — максимум Minimum Мінімум Justification Вирівнювання за шириною Add filters from the list above Додайте фільтри зі списку вище @@ -7028,6 +7063,24 @@ breakText Glyphs Гліфи # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Розібрати штрихи на контури @msg select paths with dashed strokes to expand виділіть контури зі штриховим обведенням для розбору +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Дотичне коло… + Tangent Circle Дотичне коло + Circle: Коло: +@msg `ids` names an object twice `ids` указує об’єкт двічі +@msg select two or three paths or compound paths виділіть два або три контури чи складені контури +@msg `radius` must be from 0.01 to 1000000 pt `radius` має бути від 0.01 до 1000000 pt +@msg two shapes need a `radius` для двох фігур потрібен `radius` +@msg three shapes set the radius themselves: leave `radius` out три фігури самі задають радіус: не вказуйте `radius` +@msg `circle` must be from 0 to 64 `circle` має бути від 0 до 64 +@msg a shape has no outline фігура не має контуру +@msg the shapes are too complex: at most 2000 segments in all фігури надто складні: загалом не більше 2000 сегментів +@msg these shapes take too long to search пошук для цих фігур триває надто довго +@msg more than 64 circles touch these shapes: they may touch along a whole curve цих фігур торкається понад 64 кола: можливо, вони торкаються вздовж цілої кривої +@msg no circle touches these shapes жодне коло не торкається цих фігур +@msg `circle` is past the last circle found ({found}) `circle` більше за кількість знайдених кіл ({found}) +@msg object {value} is not a path or compound path об’єкт {value} не є контуром чи складеним контуром +@msg these shapes are too small to measure ці фігури замалі для вимірювання # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Інструменти документа Save a Timestamped Copy Зберегти копію з датою і часом @@ -7082,7 +7135,7 @@ breakText Glyphs Гліфи @msg stroke cannot be set on a symbol instance stroke не можна задати для екземпляра символу @msg fill on a symbol instance must be a solid color or none fill екземпляра символу має бути суцільним кольором або none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it {key} не можна задати для зображення без ефекту «Перетворити на фігуру» або «Обвести об’єкт» -@msg pass newName, registration, exportType, nineSlice and/or type вкажіть newName, registration, exportType, nineSlice та/або type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid вкажіть newName, registration, exportType, nineSlice, type та/або alignToPixelGrid Text Flow Потік тексту By Rows За рядками By Columns За стовпцями @@ -8665,7 +8718,9 @@ breakText Glyphs Гліфи @msg position must be normal, superscript or subscript position має бути normal, superscript або subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position має бути topLeft, topRight, bottomLeft або bottomRight @msg positions must be between 0 and 100000 pt positions мають бути від 0 до 100000 pt +@msg ppi can't be more than {max} for this image ppi для цього зображення не може перевищувати {max} @msg ppi must be a positive number, not {ppi} ppi має бути додатним числом, а не {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim залишає пікселі зображення без змін: не вказуйте ppi @msg ppi must be between 1 and 2400 ppi має бути від 1 до 2400 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` не є transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape має бути clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 862ab8d8ae..adbe7bdb6f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1589,6 +1589,8 @@ file-filter Templates Mẫu Font Family & Style Họ phông & kiểu Font Family, Style & Size Họ phông, kiểu & cỡ Font List Danh sách phông + Show Similar Fonts Hiển thị phông tương tự + Clear Similar Fonts Xóa phông tương tự Font Preview Size Cỡ xem trước phông Font Size Cỡ chữ Variable Font Phông chữ biến thiên @@ -2008,6 +2010,10 @@ digits Hindi Hindi Cap Height Chiều cao chữ hoa x-Height Chiều cao chữ x ICF Box Ô ICF + Show Sample Hiện mẫu + Hide Sample Ẩn mẫu + Max Ascent/Descent Độ cao/sâu tối đa + Max Ascender Nét chân chữ trên tối đa ICF Top/Right ICF Trên/Phải Identify Objects By Nhận diện đối tượng theo Ignore Bỏ qua @@ -3651,6 +3657,8 @@ mark-style Japanese Kiểu Nhật @msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1} Search commands and tools Tìm kiếm lệnh và công cụ Search commands and tools… Tìm kiếm lệnh và công cụ… + Recent Commands Lệnh gần đây + No recent commands Không có lệnh gần đây Search Commands… Tìm kiếm lệnh… Search Fonts Folder Tìm kiếm thư mục phông chữ Searching… Đang tìm kiếm… @@ -4943,6 +4951,44 @@ theme Appearance Giao diện @msg $.evalFile requires a file path $.evalFile cần đường dẫn tệp @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: thời gian chờ phải là một số mili giây hữu hạn, từ 0 trở lên @msg $.evalFile: takes a file path and a timeout $.evalFile: nhận một đường dẫn tệp và một thời gian chờ +@msg assignment to a constant binding gán cho một ràng buộc hằng +@msg invalid array length độ dài mảng không hợp lệ +@msg array literal too long literal mảng quá dài +@msg the value is not a function giá trị không phải là hàm +@msg apply was called on a value that is not a function apply được gọi trên một giá trị không phải là hàm +@msg the argument list is not an object danh sách đối số không phải là đối tượng +@msg too many arguments quá nhiều đối số +@msg the value is not a constructor giá trị không phải là hàm tạo +@msg cannot convert the object to a primitive value không thể chuyển đối tượng thành giá trị nguyên thủy +@msg cannot convert undefined or null to an object không thể chuyển undefined hoặc null thành đối tượng +@msg the right side of 'in' is not an object vế phải của 'in' không phải là đối tượng +@msg the right side of 'instanceof' is not a function vế phải của 'instanceof' không phải là hàm +@msg the function's prototype is not an object nguyên mẫu của hàm không phải là đối tượng +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} chưa được định nghĩa +@msg cannot read property '{key}' of {base} không thể đọc thuộc tính '{key}' của {base} +@msg cannot set property '{key}' of {base} không thể đặt thuộc tính '{key}' của {base} +@msg cannot read a property of {base} không thể đọc thuộc tính của {base} +@msg cannot set a property of {base} không thể đặt thuộc tính của {base} +@msg cannot define property '{key}': {why} không thể định nghĩa thuộc tính '{key}': {why} +@msg cannot assign to property '{key}': {why} không thể gán cho thuộc tính '{key}': {why} +@msg cannot delete property '{key}' không thể xóa thuộc tính '{key}' +@msg cannot declare function {ident} không thể khai báo hàm {ident} +@msg invalid assignment target đích gán không hợp lệ +@msg the array's length is read-only độ dài của mảng là chỉ đọc +@msg the property cannot be redefined không thể định nghĩa lại thuộc tính +@msg the object is not extensible đối tượng không thể mở rộng +@msg the length cannot be redefined không thể định nghĩa lại độ dài +@msg it is read-only nó là chỉ đọc +@msg an element cannot be deleted không thể xóa một phần tử +@msg it has only a getter nó chỉ có getter +@msg the value is a primitive giá trị là kiểu nguyên thủy @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: dòng {line}, cột {column} của {file}: {e} (đã ném) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: dòng {line}, cột {column}: {e} (đã ném) @msg {name}: {e} (thrown) {name}: {e} (đã ném) @@ -5075,6 +5121,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg every numbered name for {name} is taken in the document's folder mọi tên đánh số cho {name} đã được dùng trong thư mục tài liệu @msg every search thread stopped on an internal error (please report this bug) mọi luồng tìm kiếm đã dừng do lỗi nội bộ (vui lòng báo cáo lỗi này) @msg Expand Appearance: the selection has a basic appearance Mở rộng diện mạo: vùng chọn có diện mạo cơ bản +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all một số hiệu ứng raster không được chuyển thành hình ảnh: chúng sẽ cần hơn 1.024 hình ảnh hoặc tổng cộng 256 megapixel @msg Expand: no brush strokes selected Mở rộng: chưa chọn nét cọ @msg Expand: no gradient fills Mở rộng: không có tô chuyển sắc @msg Expand: nothing to expand Mở rộng: không có gì để mở rộng @@ -5944,7 +5991,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg Unknown dimension style Kiểu kích thước không xác định @msg Unknown unit Đơn vị không xác định # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. Đóng các đầu tròn của biên dạng mở. Khi xoay một phần, các mặt cắt bên vẫn mở. + Close the circular ends of open profiles. Partial sweeps also close their cut sides. Đóng các đầu tròn của biên dạng mở. Khi xoay một phần, các mặt cắt bên cũng được đóng. Distance Khoảng cách @msg span must be "object" or "selection", got {v} span phải là "object" hoặc "selection", không phải {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" đặt một `gradient`, không phải mẫu màu @@ -6098,6 +6145,7 @@ liquify-list-end {0}, {1} {0} và {1} Single Word Justification: Căn đều một từ: Full Justify Căn đều hoàn toàn Minimum must not exceed Desired, nor Desired Maximum. Giá trị tối thiểu không được vượt quá giá trị mong muốn, và giá trị mong muốn không được vượt quá tối đa. +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: giá trị tối thiểu không được vượt quá giá trị mong muốn, và giá trị mong muốn không được vượt quá tối đa Minimum Tối thiểu Justification Căn đều Add filters from the list above Thêm bộ lọc từ danh sách phía trên @@ -7045,6 +7093,24 @@ breakText Glyphs Glyph # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Mở rộng nét đứt thành đường dẫn @msg select paths with dashed strokes to expand chọn các đường dẫn có nét đứt để mở rộng +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… Đường tròn tiếp xúc… + Tangent Circle Đường tròn tiếp xúc + Circle: Đường tròn: +@msg `ids` names an object twice `ids` nêu một đối tượng hai lần +@msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp +@msg `radius` must be from 0.01 to 1000000 pt `radius` phải từ 0.01 đến 1000000 pt +@msg two shapes need a `radius` hai hình cần `radius` +@msg three shapes set the radius themselves: leave `radius` out ba hình tự xác định bán kính: hãy bỏ `radius` +@msg `circle` must be from 0 to 64 `circle` phải từ 0 đến 64 +@msg a shape has no outline một hình không có đường viền +@msg the shapes are too complex: at most 2000 segments in all các hình quá phức tạp: tổng cộng tối đa 2000 đoạn +@msg these shapes take too long to search việc tìm kiếm cho các hình này mất quá nhiều thời gian +@msg more than 64 circles touch these shapes: they may touch along a whole curve hơn 64 đường tròn chạm vào các hình này: có thể chúng chạm dọc theo cả một đường cong +@msg no circle touches these shapes không có đường tròn nào chạm vào các hình này +@msg `circle` is past the last circle found ({found}) `circle` vượt quá đường tròn cuối cùng tìm được ({found}) +@msg object {value} is not a path or compound path đối tượng {value} không phải đường dẫn hay đường dẫn phức hợp +@msg these shapes are too small to measure các hình này quá nhỏ để đo # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools Công cụ tài liệu Save a Timestamped Copy Lưu bản sao có ngày giờ @@ -7099,7 +7165,7 @@ breakText Glyphs Glyph @msg stroke cannot be set on a symbol instance không thể đặt stroke cho thực thể ký hiệu @msg fill on a symbol instance must be a solid color or none fill của thực thể ký hiệu phải là màu đặc hoặc none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it không thể đặt {key} cho hình ảnh không có hiệu ứng Chuyển thành hình dạng hoặc Đường bao đối tượng -@msg pass newName, registration, exportType, nineSlice and/or type hãy cung cấp newName, registration, exportType, nineSlice và/hoặc type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid hãy cung cấp newName, registration, exportType, nineSlice, type và/hoặc alignToPixelGrid Text Flow Luồng văn bản By Rows Theo hàng By Columns Theo cột diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7a20e57988..180e2ba8bb 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -976,6 +976,10 @@ antiAlias Sharp 锐利 Cap Height 大写字母高度 x-Height x 字高 ICF Box ICF 框 + Show Sample 显示样本 + Hide Sample 隐藏样本 + Max Ascent/Descent 最大上升/下降 + Max Ascender 最大上伸部 Em Dash 长破折号 Em Space 全角空格 Embed 嵌入 @@ -1297,6 +1301,8 @@ file-filter Templates 模板 Font Family & Style 字体系列和样式 Font Family, Style & Size 字体系列、样式和字号 Font List 字体列表 + Show Similar Fonts 显示相似字体 + Clear Similar Fonts 清除相似字体 Font Preview Size 字体预览大小 Font Size 字号 Variable Font 可变字体 @@ -3136,6 +3142,8 @@ digits Malayalam 马拉雅拉姆数字 Filter Layers Panel Rows 筛选图层面板行 Search commands and tools 搜索命令和工具 Search commands and tools… 搜索命令和工具… + Recent Commands 最近使用的命令 + No recent commands 没有最近使用的命令 Search Commands… 搜索命令… Secondary 次要 Section Symbol 章节符号 @@ -4318,6 +4326,7 @@ imageTrace Outline 轮廓 @msg no history to clear 没有可清除的历史记录 @msg no history state {v} 没有历史记录状态 {v} @msg Expand Appearance: the selection has a basic appearance 扩展外观:所选对象只有基本外观 +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 部分栅格效果未转换为图像:它们会超过 1,024 个图像或总计 256 兆像素 @msg select (or target) objects whose appearance isn't basic 请选择 (或定位) 外观不是基本外观的对象 @msg {C}: no effect at index {from} {C}:索引 {from} 处没有效果 @msg Expand: no gradient fills 扩展:没有渐变填色 @@ -4963,6 +4972,31 @@ imageTrace Outline 轮廓 @msg $.evalFile requires a file path $.evalFile 需要文件路径 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile:超时必须是 0 或更大的有限毫秒数 @msg $.evalFile: takes a file path and a timeout $.evalFile:接受一个文件路径和一个超时值 +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} 未定义 +@msg cannot read property '{key}' of {base} 无法读取 {base} 的属性 '{key}' +@msg cannot set property '{key}' of {base} 无法设置 {base} 的属性 '{key}' +@msg cannot read a property of {base} 无法读取 {base} 的属性 +@msg cannot set a property of {base} 无法设置 {base} 的属性 +@msg cannot define property '{key}': {why} 无法定义属性 '{key}':{why} +@msg cannot assign to property '{key}': {why} 无法为属性 '{key}' 赋值:{why} +@msg cannot delete property '{key}' 无法删除属性 '{key}' +@msg cannot declare function {ident} 无法声明函数 {ident} +@msg invalid assignment target 赋值目标无效 +@msg the array's length is read-only 数组的长度是只读的 +@msg the property cannot be redefined 属性无法重新定义 +@msg the object is not extensible 对象不可扩展 +@msg the length cannot be redefined 长度无法重新定义 +@msg it is read-only 它是只读的 +@msg an element cannot be deleted 无法删除元素 +@msg it has only a getter 它只有 getter +@msg the value is a primitive 该值是原始值 @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}:{file} 第 {line} 行,第 {column} 列:{e}(抛出) @msg {name}: line {line}, column {column}: {e} (thrown) {name}:第 {line} 行,第 {column} 列:{e}(抛出) @msg {name}: {e} (thrown) {name}:{e}(抛出) @@ -6175,7 +6209,7 @@ lighting Light 光源 @msg Choose a circle or a perfect arc 请选择圆或标准圆弧 @msg Choose a precision from 0 to 6 请选择 0 到 6 之间的精度 # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 封闭开放轮廓的圆形端部。部分旋转的切割侧面保持开放。 + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 封闭开放轮廓的圆形端部。部分旋转的切割侧面也会封闭。 Distance 距离 Make Image Dynamic 使图像动态化 Import Data Sets… 导入数据集… @@ -6318,6 +6352,7 @@ lighting Light 光源 Single Word Justification: 单字对齐: Full Justify 全部强制双齐 Minimum must not exceed Desired, nor Desired Maximum. 最小值不能超过所需值,所需值不能超过最大值。 +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`:最小值不能超过所需值,所需值不能超过最大值 Minimum 最小值 Justification 对齐设置 Add filters from the list above 从上方列表添加滤镜 @@ -7260,6 +7295,24 @@ breakText Glyphs 字形 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 将短划线扩展为路径 @msg select paths with dashed strokes to expand 请选择要扩展的虚线描边路径 +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… 相切圆… + Tangent Circle 相切圆 + Circle: 圆: +@msg `ids` names an object twice `ids` 重复指定了同一个对象 +@msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 +@msg `radius` must be from 0.01 to 1000000 pt `radius` 必须为 0.01 到 1000000 pt +@msg two shapes need a `radius` 两个形状需要 `radius` +@msg three shapes set the radius themselves: leave `radius` out 三个形状会自行确定半径:请省略 `radius` +@msg `circle` must be from 0 to 64 `circle` 必须为 0 到 64 +@msg a shape has no outline 有一个形状没有轮廓 +@msg the shapes are too complex: at most 2000 segments in all 形状过于复杂:总共最多 2000 个线段 +@msg these shapes take too long to search 这些形状的搜索耗时过长 +@msg more than 64 circles touch these shapes: they may touch along a whole curve 与这些形状相切的圆超过 64 个:它们可能沿整条曲线相接 +@msg no circle touches these shapes 没有与这些形状相切的圆 +@msg `circle` is past the last circle found ({found}) `circle` 超出了找到的最后一个圆({found}) +@msg object {value} is not a path or compound path 对象 {value} 不是路径或复合路径 +@msg these shapes are too small to measure 这些形状太小,无法测量 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 文档工具 Save a Timestamped Copy 保存带时间戳的副本 @@ -7314,7 +7367,7 @@ breakText Glyphs 字形 @msg stroke cannot be set on a symbol instance 无法为符号实例设置 stroke @msg fill on a symbol instance must be a solid color or none 符号实例的 fill 必须是纯色或 none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 无法为没有“转换为形状”或“轮廓化对象”效果的图像设置 {key} -@msg pass newName, registration, exportType, nineSlice and/or type 请提供 newName、registration、exportType、nineSlice 和/或 type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid 请提供 newName、registration、exportType、nineSlice、type 和/或 alignToPixelGrid Text Flow 文本流向 By Rows 按行 By Columns 按列 @@ -8924,7 +8977,9 @@ breakText Glyphs 字形 @msg position must be normal, superscript or subscript position 必须是 normal、superscript 或 subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position 必须是 topLeft、topRight、bottomLeft 或 bottomRight @msg positions must be between 0 and 100000 pt positions 必须介于 0 到 100000 pt 之间 +@msg ppi can't be more than {max} for this image 此图像的 ppi 不能超过 {max} @msg ppi must be a positive number, not {ppi} ppi 必须是正数,不能是 {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim 会保持图像像素不变:请省略 ppi @msg ppi must be between 1 and 2400 ppi 必须介于 1 到 2400 之间 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape 必须是 clippingMask|transparency diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 396a40436d..3164f6182f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1007,6 +1007,10 @@ font-technology Variable 可變 Cap Height 大寫字母高度 x-Height x 字高 ICF Box ICF 框 + Show Sample 顯示樣本 + Hide Sample 隱藏樣本 + Max Ascent/Descent 最大上升/下降 + Max Ascender 最大上伸部 Em Dash 長破折號 Em Space 全形空格 Embed 嵌入 @@ -1332,6 +1336,8 @@ file-filter Templates 範本 Font Family & Style 字體家族與樣式 Font Family, Style & Size 字體家族、樣式與大小 Font List 字體清單 + Show Similar Fonts 顯示相似字體 + Clear Similar Fonts 清除相似字體 Font Preview Size 字體預覽大小 Font Size 字體大小 Variable Font 可變字體 @@ -1953,6 +1959,7 @@ file-filter Templates 範本 @msg no history to clear 沒有可清除的步驟記錄 @msg no history state {v} 沒有步驟記錄 {v} @msg Expand Appearance: the selection has a basic appearance 展開外觀:選取範圍只有基本外觀 +@msg some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all 部分點陣效果未轉換為影像:它們會超過 1,024 個影像或總計 256 百萬像素 @msg select (or target) objects whose appearance isn't basic 請選取 (或指定目標) 外觀不是基本外觀的物件 @msg {C}: no effect at index {from} {C}:索引 {from} 處沒有效果 @msg Expand: no gradient fills 展開:沒有漸層填色 @@ -2599,6 +2606,31 @@ file-filter Templates 範本 @msg $.evalFile requires a file path $.evalFile 需要檔案路徑 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile:逾時必須是 0 或更大的有限毫秒數 @msg $.evalFile: takes a file path and a timeout $.evalFile:接受一個檔案路徑和一個逾時值 +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} 未定義 +@msg cannot read property '{key}' of {base} 無法讀取 {base} 的屬性 '{key}' +@msg cannot set property '{key}' of {base} 無法設定 {base} 的屬性 '{key}' +@msg cannot read a property of {base} 無法讀取 {base} 的屬性 +@msg cannot set a property of {base} 無法設定 {base} 的屬性 +@msg cannot define property '{key}': {why} 無法定義屬性 '{key}':{why} +@msg cannot assign to property '{key}': {why} 無法為屬性 '{key}' 賦值:{why} +@msg cannot delete property '{key}' 無法刪除屬性 '{key}' +@msg cannot declare function {ident} 無法宣告函式 {ident} +@msg invalid assignment target 賦值目標無效 +@msg the array's length is read-only 陣列的長度是唯讀的 +@msg the property cannot be redefined 屬性無法重新定義 +@msg the object is not extensible 物件不可擴充 +@msg the length cannot be redefined 長度無法重新定義 +@msg it is read-only 它是唯讀的 +@msg an element cannot be deleted 無法刪除元素 +@msg it has only a getter 它只有 getter +@msg the value is a primitive 該值是基本值 @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}:{file} 第 {line} 行,第 {column} 欄:{e}(擲回) @msg {name}: line {line}, column {column}: {e} (thrown) {name}:第 {line} 行,第 {column} 欄:{e}(擲回) @msg {name}: {e} (thrown) {name}:{e}(擲回) @@ -4416,6 +4448,8 @@ digits Malayalam 馬來亞拉姆數字 Filter Layers Panel Rows 篩選圖層面板列 Search commands and tools 搜尋指令與工具 Search commands and tools… 搜尋指令與工具… + Recent Commands 最近使用的指令 + No recent commands 沒有最近使用的指令 Search Commands… 搜尋指令… Secondary 次要 Section Symbol 章節符號 @@ -6010,7 +6044,7 @@ lighting Light 光源 X: X: Y: Y: # Revolve cap description - Close the circular ends of open profiles. Partial sweeps keep their cut sides open. 封閉開放輪廓的圓形端部。部分旋轉的切割側面保持開放。 + Close the circular ends of open profiles. Partial sweeps also close their cut sides. 封閉開放輪廓的圓形端部。部分旋轉的切割側面也會封閉。 Distance 距離 Make Image Dynamic 使影像動態化 Import Data Sets… 匯入資料集… @@ -6116,6 +6150,7 @@ lighting Light 光源 Single Word Justification: 單字對齊: Full Justify 全部強迫齊行 Minimum must not exceed Desired, nor Desired Maximum. 最小值不可超過所需值,所需值不可超過最大值。 +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`:最小值不可超過所需值,所需值不可超過最大值 Minimum 最小值 Justification 對齊設定 Add filters from the list above 從上方清單新增濾鏡 @@ -7069,6 +7104,24 @@ breakText Glyphs 字符 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 將短破折號展開為路徑 @msg select paths with dashed strokes to expand 請選取要展開的虛線筆畫路徑 +# Path Precision Tools add-on: Tangent Circle. + Tangent Circle… 相切圓… + Tangent Circle 相切圓 + Circle: 圓: +@msg `ids` names an object twice `ids` 將同一個物件指定了兩次 +@msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 +@msg `radius` must be from 0.01 to 1000000 pt `radius` 必須為 0.01 到 1000000 pt +@msg two shapes need a `radius` 兩個形狀需要 `radius` +@msg three shapes set the radius themselves: leave `radius` out 三個形狀會自行決定半徑:請勿指定 `radius` +@msg `circle` must be from 0 to 64 `circle` 必須為 0 到 64 +@msg a shape has no outline 有一個形狀沒有外框 +@msg the shapes are too complex: at most 2000 segments in all 形狀過於複雜:總共最多 2000 個線段 +@msg these shapes take too long to search 這些形狀的搜尋耗時過長 +@msg more than 64 circles touch these shapes: they may touch along a whole curve 與這些形狀相切的圓超過 64 個:它們可能沿整條曲線相接 +@msg no circle touches these shapes 沒有與這些形狀相切的圓 +@msg `circle` is past the last circle found ({found}) `circle` 超出了找到的最後一個圓({found}) +@msg object {value} is not a path or compound path 物件 {value} 不是路徑或複合路徑 +@msg these shapes are too small to measure 這些形狀太小,無法測量 # Document Tools add-on (Object › Plug-ins › Document Tools): Save a Timestamped Copy. Document Tools 文件工具 Save a Timestamped Copy 儲存附時間戳記的拷貝 @@ -7123,7 +7176,7 @@ breakText Glyphs 字符 @msg stroke cannot be set on a symbol instance 無法為符號範例設定 stroke @msg fill on a symbol instance must be a solid color or none 符號範例的 fill 必須是純色或 none @msg {key} cannot be set on an image without a Convert to Shape or Outline Object effect on it 無法為沒有「轉換為形狀」或「外框物件」效果的影像設定 {key} -@msg pass newName, registration, exportType, nineSlice and/or type 請提供 newName、registration、exportType、nineSlice 和/或 type +@msg pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid 請提供 newName、registration、exportType、nineSlice、type 和/或 alignToPixelGrid Text Flow 文字流向 By Rows 依列 By Columns 依欄 @@ -8852,7 +8905,9 @@ breakText Glyphs 字符 @msg position must be normal, superscript or subscript position 必須是 normal、superscript 或 subscript @msg position must be topLeft, topRight, bottomLeft or bottomRight position 必須是 topLeft、topRight、bottomLeft 或 bottomRight @msg positions must be between 0 and 100000 pt positions 必須介於 0 到 100000 pt 之間 +@msg ppi can't be more than {max} for this image 此影像的 ppi 不能超過 {max} @msg ppi must be a positive number, not {ppi} ppi 必須是正數,而非 {ppi} +@msg trim keeps the image's pixels as they are: leave out ppi trim 會保持影像像素不變:請勿指定 ppi @msg ppi must be between 1 and 2400 ppi 必須介於 1 和 2400 之間 @msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` 不是 transforms|bounds|fileDimensions|fit|fill @msg preserveShape must be clippingMask|transparency preserveShape 必須是 clippingMask|transparency diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 32db24c1c7..3e48476a1a 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -77,6 +77,9 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) } crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), + crate::addons::pathtools::tangent_circle::COMMAND => { + (crate::addons::pathtools::tangent_circle::KIND, crate::addons::pathtools::tangent_circle::fields(app)) + } crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), crate::addons::typetools::COMMAND => (crate::addons::typetools::KIND, crate::addons::typetools::fields(app)), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e4806b0457..de2f3ab7a1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -855,7 +855,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.cropImage", "Crop Image", "", - "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box. → {tool}; a tool that cannot be chosen returns the error", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect, ppi?}: ppi when a resolution that changes the image's pixels is set, and for a turned or skewed image its own when none is and it can be cropped to it), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box; {key: \"ppi\", value: 1 to 2400 and at most the selected image's own resolution (300 for a linked image), or null for the image's own} the cropped image's resolution; {key: \"reference\", value: 0 to 8, left to right and top to bottom; 4, the center, by default} the point the Control bar's X and Y name and its W and H resize about; {key: \"linked\", value: true or false (default false)} whether W and H keep the box's proportions. → {tool}; a tool that cannot be chosen returns the error", ), ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), ( diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 3e7fb53316..da3d1052b4 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -136,6 +136,45 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } +/// How many picks the Recent Commands list beside the search field holds. +pub(crate) const MAX_RECENT_COMMANDS: usize = 5; + +/// How many ids the saved Recent Commands list holds at most, unavailable ones included. +const MAX_SAVED_RECENT_COMMANDS: usize = 4 * MAX_RECENT_COMMANDS; + +/// Puts `id` first in the Recent Commands ids `list`, removing its earlier place, and keeps the +/// newest [`MAX_RECENT_COMMANDS`] ids that are `known`. An id that is not `known` now (a plug-in +/// that is disabled or not loaded yet) keeps its place among them, so it shows again when its +/// command comes back. The list never holds more than [`MAX_SAVED_RECENT_COMMANDS`] ids. +fn remember(list: &mut Vec, id: &str, known: impl Fn(&str) -> bool) { + list.retain(|c| c != id); + list.insert(0, id.to_string()); + let mut kept = 0; + let end = list.iter().position(|c| { + if known(c) { + kept += 1; + } + kept > MAX_RECENT_COMMANDS + }); + list.truncate(end.unwrap_or(list.len()).min(MAX_SAVED_RECENT_COMMANDS)); +} + +/// The entries the Recent Commands list shows for the ids `ids`, most recent first. An id with no +/// entry (a removed plug-in) is skipped. +fn recent<'a>(entries: &'a [Entry], ids: &[String]) -> Vec<&'a Entry> { + ids.iter().take(MAX_SAVED_RECENT_COMMANDS).filter_map(|id| entries.iter().find(|e| e.id == *id)).take(MAX_RECENT_COMMANDS).collect() +} + +/// The id of the Recent Commands list's popup. +fn recent_list_id() -> egui::Id { + egui::Id::unique("palette-recent-commands") +} + +/// Is the palette's Recent Commands list open? +pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { + egui::Popup::is_id_open(ctx, recent_list_id()) +} + pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !app.ui.palette_open { return; @@ -145,7 +184,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let q = app.ui.palette_query.to_lowercase(); let entries = entries(ctx, crate::i18n::current()); let matches: Vec<&Entry> = entries.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).take(14).collect(); + let recent = recent(&entries, &app.ui.recent_commands); + // While the Recent Commands list is open, the arrow keys and Enter go to its rows, and the + // search field leaves them the keyboard. + let list_open = recent_list_open(ctx); let mut run: Option = None; + let mut history_focused = false; // The highlighted result (#1757): Up and Down move it (wrapping), the pointer over a result // takes it, and a new query starts again from the first. let sel_id = egui::Id::unique("palette-selected"); @@ -153,8 +197,32 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if last_q != q { sel = 0; } + // The Recent Commands row with the keyboard: Up and Down move it, wrapping at the ends, so the + // keys never leave the list for the results below it. + let rsel_id = egui::Id::unique("palette-recent-selected"); + let mut rsel = if list_open { ctx.data(|d| d.get_temp::(rsel_id)).unwrap_or(0) } else { 0 }; + if list_open && !recent.is_empty() { + let rn = recent.len(); + let (down, up) = + ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp))); + if down { + rsel = (rsel + 1) % rn; + } + if up { + rsel = (rsel + rn - 1) % rn; + } + rsel = rsel.min(rn - 1); + } + // Enter or Space runs the row the arrow keys of this frame moved to. The keys are taken here, + // since a row's button turns them into a click of the row that had the keyboard last frame. + if list_open + && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter) | i.consume_key(egui::Modifiers::NONE, egui::Key::Space)) + && let Some(e) = recent.get(rsel) + { + run = Some(e.id.clone()); + } let n = matches.len(); - if n > 0 { + if n > 0 && !list_open { let (down, up) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp))); if down { @@ -168,13 +236,38 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, 90.0]).show(ctx, |ui| { egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(10)).show(ui, |ui| { ui.set_width(520.0); - let r = ui.add( - egui::TextEdit::singleline(&mut app.ui.palette_query) - .align(egui::Align2::LEFT_CENTER) - .hint_text(tl!("Search commands and tools…")) - .desired_width(500.0), - ); - r.request_focus(); + ui.horizontal(|ui| { + let r = ui.add( + egui::TextEdit::singleline(&mut app.ui.palette_query) + .align(egui::Align2::LEFT_CENTER) + .hint_text(tl!("Search commands and tools…")) + .desired_width(470.0), + ); + // Recent Commands: the last picks, most recent first. A choice runs as a pick of + // the same result does. The first row takes the keyboard when the list opens, and + // the row with the keyboard keeps it while the list is open. + let button = crate::widgets::icon_button(ui, "history", tl!("Recent Commands"), false, 24.0); + // The search field keeps the keyboard, except while the list is open or Tab has + // moved it to the list's button, where Enter or Space opens the list. + history_focused = button.has_focus(); + if !list_open && !history_focused { + r.request_focus(); + } + egui::Popup::menu(&button).id(recent_list_id()).show(|ui| { + if recent.is_empty() { + ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); + } + for (i, e) in recent.iter().enumerate() { + let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); + if i == rsel { + row.request_focus(); + } + if row.clicked() { + run = Some(e.id.clone()); + } + } + }); + }); ui.add_space(6.0); for (i, e) in matches.iter().enumerate() { let resp = ui.add( @@ -190,16 +283,22 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { run = Some(e.id.clone()); } } - if ui.input(|i| i.key_pressed(egui::Key::Enter)) + if !list_open + && !history_focused + && ui.input(|i| i.key_pressed(egui::Key::Enter)) && let Some(e) = matches.get(sel) { run = Some(e.id.clone()); } }); }); - ctx.data_mut(|d| d.insert_temp(sel_id, (sel, q))); + ctx.data_mut(|d| { + d.insert_temp(sel_id, (sel, q)); + d.insert_temp(rsel_id, rsel); + }); if let Some(id) = run { app.ui.palette_open = false; + remember(&mut app.ui.recent_commands, &id, |c| entries.iter().any(|e| e.id == c)); run_pick(app, &id); } } @@ -512,6 +611,268 @@ mod tests { } } + /// #6376: a pick goes first in Recent Commands, and a pick of a command already listed moves it + /// to the top, so each command takes one place. The list is saved with the UI state. + #[test] + fn recent_commands_put_the_latest_pick_first_and_list_each_command_once() { + let mut list = vec![]; + for id in ["object.group", "paint.swap", "object.group"] { + remember(&mut list, id, |_| true); + } + assert_eq!(list, ["object.group", "paint.swap"]); + // A pick with Enter in the open palette is remembered. + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.recent_commands = list; + app.ui.palette_open = true; + app.ui.palette_query = "paint.swap".into(); + let first = build(crate::i18n::current()).into_iter().find(|e| e.haystack.contains("paint.swap")).unwrap().id; + let ctx = egui::Context::default(); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + ctx.run_ui(egui::RawInput { events: vec![enter], ..Default::default() }, |ui| show(&mut app, ui.ctx())).textures_delta.clear(); + assert!(!app.ui.palette_open); + assert_eq!(app.ui.recent_commands.first(), Some(&first)); + assert_eq!(app.ui.recent_commands.iter().filter(|c| **c == first).count(), 1, "{:?}", app.ui.recent_commands); + let restored: crate::state::UiState = serde_json::from_str(&serde_json::to_string(&app.ui).unwrap()).unwrap(); + assert_eq!(restored.recent_commands, app.ui.recent_commands); + } + + /// #6376: Recent Commands keeps the last five picks. + #[test] + fn recent_commands_keep_the_last_five_picks() { + let mut list = vec![]; + let ids = ["a", "b", "c", "d", "e", "f", "g"]; + for id in ids { + remember(&mut list, id, |_| true); + } + assert_eq!(list, ["g", "f", "e", "d", "c"]); + let entries = build(Lang::EN); + let many: Vec = entries.iter().take(MAX_RECENT_COMMANDS + 2).map(|e| e.id.clone()).collect(); + assert_eq!(recent(&entries, &many).len(), MAX_RECENT_COMMANDS); + } + + /// #6376: a command that does not exist now, such as a plug-in's filter while the plug-in is + /// not loaded, is left out of Recent Commands. A pick keeps it in the saved list, so it shows + /// again when the command comes back; five other commands picked after it push it out. + #[test] + fn recent_commands_skip_ids_that_no_longer_exist() { + let entries = build(Lang::EN); + let known = |c: &str| entries.iter().any(|e| e.id == c); + let saved: Vec = ["plugin:test.UI.palette_removed", "object.group", "tool:no-such-tool"].map(str::to_string).into(); + let shown: Vec<&str> = recent(&entries, &saved).iter().map(|e| e.id.as_str()).collect(); + assert_eq!(shown, ["object.group"]); + let mut list = saved; + remember(&mut list, "paint.swap", known); + assert_eq!(list, ["paint.swap", "plugin:test.UI.palette_removed", "object.group", "tool:no-such-tool"]); + let four: Vec = entries.iter().filter(|e| e.id != "paint.swap" && e.id != "object.group").take(4).map(|e| e.id.clone()).collect(); + for id in &four { + remember(&mut list, id, known); + } + let expected: Vec = + four.iter().rev().cloned().chain(["paint.swap".to_string(), "plugin:test.UI.palette_removed".to_string()]).collect(); + assert_eq!(list, expected, "object.group, the sixth known id, and the ids after it go"); + // Unavailable ids are capped too. + let mut list: Vec = (0..50).map(|i| format!("plugin:test.UI.gone{i}")).collect(); + remember(&mut list, "paint.swap", known); + assert_eq!(list.len(), MAX_SAVED_RECENT_COMMANDS); + assert_eq!(list.first().map(String::as_str), Some("paint.swap")); + } + + /// The open palette drawn over `app`, after the frame's keys go to the shortcuts as in the app, + /// with a query no result matches, so the only command buttons are the Recent Commands list's. + fn palette_harness(mut app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + app.ui.palette_open = true; + app.ui.palette_query = "zzqqxxjj".into(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 700.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + h + } + + /// #6376: the open Recent Commands list has the keyboard: its first row takes it, Down moves to + /// the next row and Enter runs that row, not the highlighted search result. + #[test] + fn the_keyboard_moves_through_recent_commands_and_enter_runs_a_row() { + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into(), "paint.swap".into()]; + let mut h = palette_harness(app); + h.state_mut().ui.palette_query = "zoom".into(); + h.run_steps(1); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + h.key_press(egui::Key::ArrowDown); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(!h.state().ui.palette_open, "the palette closes"); + assert_eq!(h.state().ui.recent_commands, ["paint.swap", "object.group"]); + } + + /// #6376: Down on the last Recent Commands row wraps to the first row, and Up on the first + /// wraps to the last, so the keys never reach the search results below the list. + #[test] + fn the_keys_wrap_within_recent_commands() { + use egui_kittest::kittest::Queryable; + // (keys pressed after the list opens, the command Enter then runs) + let cases = [(vec![egui::Key::ArrowDown, egui::Key::ArrowDown], "object.group"), (vec![egui::Key::ArrowUp], "paint.swap")]; + for (keys, ran) in cases { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into(), "paint.swap".into()]; + let mut h = palette_harness(app); + h.state_mut().ui.palette_query = "zoom".into(); + h.run_steps(1); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + for key in &keys { + h.key_press(*key); + h.run_steps(2); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(!h.state().ui.palette_open, "{keys:?}: the palette closes"); + assert_eq!(h.state().ui.recent_commands.first().map(String::as_str), Some(ran), "{keys:?}: {:?}", h.state().ui.recent_commands); + assert_eq!(h.state().ui.recent_commands.len(), 2, "{keys:?}: no search result ran"); + } + } + + /// #6376: Down and Enter that arrive in the same frame run the row Down moved to, not the row + /// that had the keyboard before. + #[test] + fn down_and_enter_in_one_frame_run_the_row_down_moved_to() { + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into(), "paint.swap".into()]; + let mut h = palette_harness(app); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + // `key_press` runs a frame for each event, so both keys go into the next frame's input. + for key in [egui::Key::ArrowDown, egui::Key::Enter] { + h.input_mut().events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + } + h.run_steps(2); + assert!(!h.state().ui.palette_open, "the palette closes"); + assert_eq!(h.state().ui.recent_commands, ["paint.swap", "object.group"]); + } + + /// #6376: Tab moves the keyboard from the search field to the Recent Commands button and it + /// stays there; Enter then opens the list instead of running the highlighted result. + #[test] + fn tab_reaches_the_recent_commands_button_and_enter_opens_the_list() { + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into()]; + let mut h = palette_harness(app); + h.state_mut().ui.palette_query = "zoom".into(); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert!(h.get_by_label(tl!("Recent Commands")).is_focused(), "the button keeps the keyboard"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.palette_open, "no search result ran"); + let shown = build(crate::i18n::current()).into_iter().find(|e| e.id == "object.group").unwrap().shown; + assert!(h.query_by(|n| n.label().is_some_and(|l| l.starts_with(&shown))).is_some(), "the list is open"); + assert_eq!(h.state().ui.recent_commands, ["object.group"]); + } + + /// #6376: another open popup leaves the palette's keys alone: Enter still runs the highlighted + /// result. Only the Recent Commands list takes them. + #[test] + fn another_popup_leaves_enter_to_the_palette() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.palette_open = true; + app.ui.palette_query = "paint.swap".into(); + let first = build(crate::i18n::current()).into_iter().find(|e| e.haystack.contains("paint.swap")).unwrap().id; + let ctx = egui::Context::default(); + let other = egui::Id::unique("another popup"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for events in [vec![], vec![enter]] { + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + egui::Popup::open_id(ui.ctx(), other); + show(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + } + assert!(egui::Popup::is_id_open(&ctx, other) && !recent_list_open(&ctx)); + assert!(!app.ui.palette_open, "Enter runs the highlighted result"); + assert_eq!(app.ui.recent_commands, [first]); + } + + /// #6376: Escape with the Recent Commands list open closes the list and leaves the palette + /// open; the next Escape closes the palette. + #[test] + fn escape_closes_recent_commands_before_the_palette() { + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into()]; + let mut h = palette_harness(app); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + let shown = build(crate::i18n::current()).into_iter().find(|e| e.id == "object.group").unwrap().shown; + let row = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.query_by(|n| n.label().is_some_and(|l| l.starts_with(&shown))).is_some(); + assert!(row(&h), "the list is open"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(!row(&h), "the list closes"); + assert!(h.state().ui.palette_open, "the palette stays open"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(!h.state().ui.palette_open, "the next Escape closes the palette"); + } + + /// #6376: a choice in Recent Commands closes the palette and runs what a pick of the same + /// result runs (here Clean Up… opens its dialog), and moves the command to the top. + #[test] + fn a_recent_command_runs_what_its_pick_runs() { + use egui_kittest::kittest::Queryable; + let id = "object.path.cleanUp"; + let session = || vectorcraft_testkit::fixtures::Fixture::Single.session(); + let mut picked = VectorcraftApp::new(session(), crate::Services::default()); + picked.ui.status.clear(); + run_pick(&mut picked, id); + assert!(picked.ui.dialog.is_some(), "{}", picked.ui.status); + + let mut app = VectorcraftApp::new(session(), crate::Services::default()); + app.ui.status.clear(); + app.ui.recent_commands = vec!["object.group".into(), id.into()]; + // A result's button is named by its label and its shortcut. + let e = build(crate::i18n::current()).into_iter().find(|e| e.id == id).unwrap(); + let name = format!("{} {}", e.shown, menus::shown_shortcut(&e.shortcut)); + let mut h = palette_harness(app); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + h.get_by_label(&name).click(); + h.run_steps(2); + let app = h.state(); + assert!(!app.ui.palette_open, "the palette closes"); + assert_eq!(outcome(app), outcome(&picked)); + assert_eq!(app.ui.recent_commands, [id, "object.group"]); + } + + /// #6376: with nothing picked yet, Recent Commands shows a dimmed No recent commands row. + #[test] + fn recent_commands_without_picks_show_a_dimmed_row() { + use egui_kittest::kittest::{NodeT, Queryable}; + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut h = palette_harness(app); + assert!(h.query_by_label(tl!("No recent commands")).is_none(), "the list opens on a click"); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + assert!(h.get_by_label(tl!("No recent commands")).accesskit_node().is_disabled()); + assert!(h.state().ui.palette_open); + } + /// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts /// from the first again. #[test] diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 0ad9c369fd..b156185ff3 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -674,6 +674,12 @@ fn spectrum(ui: &mut Ui, mode: Mode, size: egui::Vec2) -> Option { /// Draw numeric paint controls, retaining live components while the color and settings match. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + show_sized(app, ui, 0.0); +} + +/// Draw the Color panel in a sized dock body; compact mixers use [`show`]. +pub(crate) fn show_sized(app: &mut VectorcraftApp, ui: &mut Ui, height: f32) { + let top = ui.next_widget_position().y; let t = Tokens::get(ui.ctx()); let tgt = target(app, ui); let color = tgt.color(); @@ -684,7 +690,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let hit = ui .horizontal(|ui| { super::proxy(app, ui, 40.0); - spectrum(ui, mode, vec2(ui.available_width(), 40.0)) + spectrum(ui, mode, vec2(ui.available_width(), height.max(40.0))) }) .inner; match hit { @@ -851,7 +857,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); ui.add_space(4.0); - match spectrum(ui, mode, vec2(ui.available_width(), 46.0)) { + // Measure from the content origin so scrolling moves the ramp without stretching it. + let remaining = height - (ui.next_widget_position().y - top); + match spectrum(ui, mode, vec2(ui.available_width(), remaining.max(46.0))) { Some(SpectrumHit::Pick(c, phase)) => pick(c, phase, &mut new), Some(SpectrumHit::Cycle) => set_mode(app, &tgt, mode.next()), Some(SpectrumHit::Recolor { invert }) => recolor(app, ui, &tgt, invert, alt), diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index bd605eef01..07295dc256 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -8,6 +8,60 @@ fn app() -> VectorcraftApp { app } +fn painted_spectrum(shape: &egui::Shape) -> Option { + match shape { + egui::Shape::Mesh(mesh) if mesh.vertices.len() > 500 => Some(mesh.calc_bounds()), + egui::Shape::Vec(shapes) => shapes.iter().find_map(painted_spectrum), + _ => None, + } +} + +/// #8005: enlarging the Color panel gives the spectrum the added vertical space. +#[test] +fn the_spectrum_grows_with_the_color_panel() { + for hidden in [false, true] { + let mut app = app(); + app.ui.color_hide_options = hidden; + let ctx = egui::Context::default(); + let mut rects = Vec::new(); + for height in [300.0, 480.0] { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, height))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, Some(ui.max_rect().bottom())); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { + crate::dock::panel_body(&mut app, ui, "color", 300.0, height - 20.0); + }); + }); + rects.push(out.shapes.iter().find_map(|shape| painted_spectrum(&shape.shape)).expect("the spectrum is painted")); + out.textures_delta.clear(); + } + assert!((rects[1].top() - rects[0].top()).abs() < 1.0, "resizing keeps the ramp's top stable"); + assert!((rects[1].height() - rects[0].height() - 180.0).abs() < 1.0, "options hidden={hidden}: {rects:?}"); + } +} + +#[test] +fn a_short_color_panel_scrolls_without_stretching_the_spectrum() { + let mut app = app(); + let ctx = egui::Context::default(); + for offset in [0.0, 100.0] { + for _ in 0..3 { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 120.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let info = egui::UiStackInfo::default().with_tag_value(crate::widgets::PANEL_FOOTER, Some(ui.max_rect().bottom())); + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { + widgets::panel_scroll(ui, egui::ScrollArea::vertical().vertical_scroll_offset(offset), |ui| { + crate::dock::panel_body(&mut app, ui, "color", 300.0, 100.0); + }); + }); + }); + let r = out.shapes.iter().find_map(|shape| painted_spectrum(&shape.shape)).expect("the spectrum is painted"); + assert!((r.height() - 46.0).abs() < 1.0, "offset={offset}: {r:?}"); + out.textures_delta.clear(); + } + } +} + /// Run the panel for one frame with `events` and `modifiers`; returns the spectrum's rect (when /// the options are shown) and the panel's height. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, modifiers: egui::Modifiers) -> (Option, f32) { diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index d99d4ad068..0dc807bd94 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -2,6 +2,10 @@ //! outlines; Show › Entire Font adds the glyphs no character maps, by glyph id. Double-click //! inserts the character at the Type tool's caret (or appends it to the selected text objects). //! The character selected with the Type tool is highlighted in the grid. +//! A character whose glyph has alternates has a triangle in its cell's lower right corner, and a +//! click on it opens a pop-up of those alternates ([`alternates_popup`]); picking one inserts the +//! character drawn with it ([`insert_alternate`]). In Entire Font a glyph no character maps has the +//! triangle too, and a pick goes on the selected character as a double-click on its cell does. //! Show › Alternates for Current Selection lists that character's alternate glyphs instead (as it //! stands in its word), and a double-click applies the OpenType feature that draws one to that //! character alone, so the text stays real text that joins its neighbors. A double-click on a @@ -373,6 +377,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let row_h = cell + ui.spacing().item_spacing.y; area = area.vertical_scroll_offset((((i / cols) as f32 + 0.5) * row_h - list_h * 0.5).max(0.0)); } + // A pick in a cell's pop-up of alternates: the character (none for a glyph no character maps), + // the glyph of its cell, the glyph picked. + let mut popup_pick: Option<(Option, u32, u32)> = None; let shown = area.show_rows(ui, cell, rows, |ui, range| { for r in range.clone() { @@ -401,6 +408,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let ink = if matches!(pick, Some(None)) { t.text_disabled } else { t.text_strong }; let tex = glyph_texture(ui.ctx(), &face, gid, px); ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), ink); + // Only the cells drawn ask whether their glyph has alternates. + if face.has_alternates(gid) + && let Some(picked) = corner_popup(ui, &face, c, gid, rect, cell) + { + popup_pick = Some((c, gid, picked)); + } // The tooltip is made when it is shown: working out why a glyph cannot be // applied reads the font, which hundreds of cells cannot do each frame. let resp = resp.on_hover_ui(|ui| { @@ -443,6 +456,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { range }); ui.ctx().data_mut(|d| d.insert_temp(follow_id, (selected, shown.inner))); + match (popup_pick, &fit) { + (Some((Some(c), cell_gid, picked)), _) => insert_alternate(app, ui.ctx(), &face, c, cell_gid, picked), + // A glyph no character maps goes on the selected character as a double-click on its cell + // in Entire Font puts it. + (Some((None, _, picked)), Some(fit)) => match fit.pick(&face, picked) { + Some(pick) => fit.apply(app, pick), + None => app.status(fit.why(&face, picked)), + }, + _ => {} + } ui.add_space(4.0); let info = ui.ctx().data(|d| d.get_temp::<(Option, u32)>(hover_id)); let count = crate::i18n::tn(total as u64, "{n} glyph", "{n} glyphs"); @@ -630,15 +653,34 @@ fn alternates(app: &mut VectorcraftApp, ui: &mut Ui, w: f32) { /// goes through `text.setRangeStyle` on exactly the character (its other alternate features are /// turned off, a glyph choice is taken away); a glyph no feature draws through /// `text.setGlyphAlternate`. The default glyph, or a variant the character already has, changes -/// nothing. -fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), features: &[String], has_choice: bool, pick: Pick) { - let (cmd, params) = match pick { +/// nothing. Whether the command ran or nothing needed to change; a failed command's error goes to +/// the status. +fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), features: &[String], has_choice: bool, pick: Pick) -> bool { + let Some((cmd, params)) = alternate_command(id, bytes, features, has_choice, pick) else { return true }; + match app.run(cmd, params) { + Ok(_) => true, + Err(e) => { + app.status(e.to_string()); + false + } + } +} + +/// The command and parameters [`apply_alternate`] runs; `None` when nothing needs to change. +fn alternate_command( + id: NodeId, + bytes: (usize, usize), + features: &[String], + has_choice: bool, + pick: Pick, +) -> Option<(&'static str, serde_json::Value)> { + Some(match pick { Pick::Glyph(gid) => ("text.setGlyphAlternate", json!({"id": id.0, "start": bytes.0, "gid": gid})), Pick::Default | Pick::Feature(_) => { let tag = if let Pick::Feature(tag) = &pick { Some(tag.as_str()) } else { None }; let changes = vectorcraft_text::alternate_changes(features, tag); if changes.is_empty() && !has_choice { - return; + return None; } let mut params = json!({"id": id.0, "start": bytes.0, "end": bytes.1}); if !changes.is_empty() { @@ -649,10 +691,7 @@ fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), } ("text.setRangeStyle", params) } - }; - if let Err(e) = app.run(cmd, params) { - app.status(e.to_string()); - } + }) } /// The most alternate glyphs the canvas shows beside a selected character. Public behavior: at @@ -944,6 +983,315 @@ fn insert_character(app: &mut VectorcraftApp, ctx: &egui::Context, face: &vector } } +/// The side of the triangle in the lower right corner of a grid cell `cell` points wide whose glyph +/// has alternates: a quarter of the cell, from 5 to 10 points (VectorCraft's own size). +fn corner_side(cell: f32) -> f32 { + (cell * 0.25).clamp(5.0, 10.0) +} + +/// The most columns, and the most rows before it scrolls, of a cell's pop-up of alternates +/// (VectorCraft's own numbers). +const POPUP_COLUMNS: usize = 8; +const POPUP_ROWS: usize = 6; + +/// The triangle in the lower right corner of the grid cell `rect` of character `c` (none for a +/// glyph no character maps), whose glyph `gid` has alternates, and the pop-up a click on it opens +/// ([`alternates_popup`]). Public +/// behavior: a pop-up of alternate glyphs opens from the triangle in the lower right corner of a +/// glyph's box where the glyph has alternates +/// ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)). +/// Returns the glyph picked in the pop-up, in the frame it is picked. +fn corner_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option, gid: u32, rect: egui::Rect, cell: f32) -> Option { + let t = Tokens::get(ui.ctx()); + let side = corner_side(cell); + let corner = egui::Rect::from_min_max(rect.max - vec2(side + 1.0, side + 1.0), rect.max - vec2(1.0, 1.0)); + let resp = ui.interact(corner, egui::Id::unique(("gl-alternates-corner", face.id(), c, gid)), Sense::click()); + let fill = if resp.hovered() { t.accent } else { t.text_dim }; + ui.painter().add(egui::Shape::convex_polygon(vec![corner.right_top(), corner.right_bottom(), corner.left_bottom()], fill, Stroke::NONE)); + let resp = resp.on_hover_text(tl!("Show Character Alternates")); + let mut picked = None; + egui::Popup::menu(&resp).show(|ui| picked = alternates_popup(ui, face, c, gid, cell.max(CELL_STEPS[CELL_DEFAULT]))); + picked +} + +/// The pop-up of the alternates of glyph `gid`: that glyph first, then the alternates +/// [`vectorcraft_text::FontFace::alternates`] lists for character `c`, or for a glyph no character +/// maps the glyphs [`vectorcraft_text::FontFace::substitutions`] gives it, in the font's order, in +/// cells `cell` points wide, [`POPUP_COLUMNS`] to a row and [`POPUP_ROWS`] rows before it scrolls. +/// The glyph clicked. +fn alternates_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option, gid: u32, cell: f32) -> Option { + let t = Tokens::get(ui.ctx()); + let mut list: Vec<(u32, Option<[u8; 4]>)> = vec![(gid, None)]; + match c { + Some(c) => list.extend(face.alternates(c).into_iter().map(|a| (a.gid, Some(a.feature)))), + None => list.extend(face.substitutions(gid).into_iter().flat_map(|s| s.glyphs.into_iter().map(move |g| (g, Some(s.feature))))), + } + let mut seen = std::collections::HashSet::new(); + list.retain(|(g, _)| seen.insert(*g)); + let cols = list.len().clamp(1, POPUP_COLUMNS); + let rows = list.len().div_ceil(cols); + let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; + let mut picked = None; + let area = egui::ScrollArea::vertical().id_salt(("gl-alternates-popup", face.id(), c, gid)).max_height(cell * POPUP_ROWS as f32); + area.show_rows(ui, cell, rows, |ui, range| { + for r in range { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + for &(g, feature) in list.iter().skip(r * cols).take(cols) { + let (rect, resp) = ui.allocate_exact_size(vec2(cell, cell), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 2, t.hover); + } + ui.painter().rect_stroke(rect.shrink(0.5), 0, Stroke::new(0.5, t.border), StrokeKind::Inside); + let tex = glyph_texture(ui.ctx(), face, g, px); + ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), t.text_strong); + let glyph = crate::i18n::fmt(tl!("glyph {id}"), &[("id", &g.to_string())]); + let tip = match feature { + Some(f) => format!("{glyph} ({})", String::from_utf8_lossy(&f)), + None => glyph, + }; + if resp.on_hover_text(tip).clicked() { + picked = Some(g); + } + } + }); + } + }); + picked +} + +/// A pick in the pop-up of character `c`'s cell, whose glyph is `gid` ([`alternates_popup`]). +/// The cell's own glyph inserts the character as a double-click on the cell does +/// ([`insert_character`]). An alternate needs the Type tool's caret or selection in text set in +/// `face`: when the selection is exactly one `c` in one type object, that character is drawn with +/// the glyph, and the selection follows it to the frame the text flows it to; else `c` goes in at the caret, in place of the selection (with the rest of a +/// threaded story that Select All selected), and is drawn with it, the two as one undo step. The +/// glyph goes on as a double-click in Show › Alternates for Current Selection puts it +/// ([`draw_selected_with`]). An Arabic presentation form goes in as its base letter, as a +/// double-click on its cell puts it, drawn with the glyph where the font gives it that glyph in its +/// word. Without a caret, with text in another font, or with a glyph the character cannot be drawn +/// with there, the status says why and nothing changes. +fn insert_alternate(app: &mut VectorcraftApp, ctx: &egui::Context, face: &vectorcraft_text::FontFace, c: char, gid: u32, picked: u32) { + if picked == gid { + return insert_character(app, ctx, face, c, gid); + } + let db = FontDb::global(); + let Some((editing, a, b)) = super::character::text_editing(app) else { + app.ui.status = "Select text or click into text with the Type tool to insert glyphs".into(); + return; + }; + let style = super::character::text_style(app).map(|(s, _)| s); + let text_face = style.as_ref().filter(|s| db.has_family(&s.font_family)).and_then(|s| db.style_face(s)); + if text_face.as_ref().map(|f| f.id()) != Some(face.id()) { + let text_font = match &text_face { + Some(f) => format!("{} {}", f.family, f.style), + None => style.map(|s| s.font_family).unwrap_or_default(), + }; + app.status(crate::i18n::fmt( + tl!("{glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font})."), + &[("glyph", &glyph_label(face, picked)), ("font", &format!("{} {}", face.family, face.style)), ("text_font", &text_font)], + )); + return; + } + let c = base_letter(face, c, gid).unwrap_or(c); + // Typing in progress stays a step of its own. + super::character::end_typing(app); + // After Select All in a threaded story, the other frames' text goes too, as typing removes it, + // even when the edited frame holds only `c`. + let story = super::character::text_story(app).unwrap_or_default(); + let one = story.is_empty() && selected_target(app).is_some_and(|t| t.ch == c && (a.min(b), a.max(b)) == (t.byte, t.byte + c.len_utf8())); + if one { + let Some(at) = app.session.active().map(|st| story_start(&st.doc, editing, &[]) + a.min(b)) else { return }; + if draw_selected_with(app, face, c, picked) { + // The glyph can change the character's width and flow it on to the next frame: the + // selection follows it there. + select_in_story(app, (editing, at), c, (0, c.len_utf8())); + } + return; + } + // Inside an undo group that is already open, the insertion and the glyph are part of that + // group's step; else they are one step of their own. + let open = app.session.active().is_some_and(|st| st.undo_group.is_some()); + if !open { + app.session.begin_named_undo_group(None); + } + put_alternate(app, face, c, picked, editing, (a.min(b), a.max(b)), &story); + if !open && let Some(st) = app.session.active_mut() { + st.undo_group = None; + } +} + +/// The insertion of [`insert_alternate`]: `c` takes the place of the Type tool's selection `lo..hi` +/// of text `id` (with the text of the other frames of `story` when the Type tool has the whole +/// threaded story selected), in the style of the selection's first character, and is drawn with +/// glyph `picked`. The edits are tried on a copy of the document first, and a pick the copy refuses +/// changes nothing, the undo history included. +fn put_alternate( + app: &mut VectorcraftApp, + face: &vectorcraft_text::FontFace, + c: char, + picked: u32, + id: NodeId, + (lo, hi): (usize, usize), + story: &[NodeId], +) { + let style = if lo < hi { + match app.run("text.getRange", json!({"id": id.0, "start": lo, "end": hi})) { + Ok(v) => v.pointer("/runs/0/style").cloned(), + Err(e) => { + app.status(e.to_string()); + return; + } + } + } else { + None + }; + let clear: Vec = story.iter().copied().filter(|f| *f != id).collect(); + let mut edit = json!({"id": id.0, "start": lo, "end": hi, "clear": clear.iter().map(|f| f.0).collect::>()}); + match style { + Some(style) => edit["runs"] = json!([{"text": c.to_string(), "style": style}]), + None => edit["insert"] = json!(c.to_string()), + } + // The character's place in the story: a full frame of threaded text flows it on to the next. + let Some(at) = app.session.active().map(|st| story_start(&st.doc, id, &clear) + lo) else { return }; + if let Err(e) = try_on_a_copy(app, face, c, picked, (id, at), &edit) { + app.status(e); + return; + } + if let Err(e) = app.run("text.editRange", edit) { + app.status(e.to_string()); + return; + } + let n = c.len_utf8(); + if select_in_story(app, (id, at), c, (0, n)) && draw_selected_with(app, face, c, picked) { + // The glyph can change the character's width and flow it on again: find it again. + select_in_story(app, (id, at), c, (n, n)); + } +} + +/// The Type tool's selection becomes bytes `start..end` from character `c` at byte `at` of the +/// story of text `id`, in the frame that holds the character; whether it is there. When that +/// frame is not the one the Type tool edits, the tool edits it, and it is selected, as a click in +/// it selects it (`move_editing_selection` in the engine's `panelcmds.rs`). +fn select_in_story(app: &mut VectorcraftApp, (id, at): (NodeId, usize), c: char, (start, end): (usize, usize)) -> bool { + let Some((frame, byte)) = app.session.active().and_then(|st| story_place(&st.doc, id, at, c)) else { return false }; + if super::character::text_editing(app).is_some_and(|(editing, ..)| editing == frame) { + app.session.set_tool_option("select", &json!({"start": byte + start, "end": byte + end})); + return true; + } + app.session.set_tool_option("textSelection", &json!({"editing": frame.0, "anchor": byte + start, "caret": byte + end})); + let selected = + app.session.active().is_some_and(|st| std::iter::successors(Some(frame), |f| st.doc.parent_of(*f)).any(|f| st.selection.contains(f))); + if !selected && let Err(e) = app.session.select(|_, sel| sel.set([frame])) { + app.status(e.to_string()); + return false; + } + true +} + +/// The bytes of the text of the frames before frame `id` in its story ([`Document::story_of`]), +/// without the frames of `clear`, whose text an edit removes. +/// +/// [`Document::story_of`]: vectorcraft_doc::Document::story_of +fn story_start(doc: &vectorcraft_doc::Document, id: NodeId, clear: &[NodeId]) -> usize { + doc.story_of(id) + .into_iter() + .take_while(|f| *f != id) + .filter(|f| !clear.contains(f)) + .filter_map(|f| match doc.node(f).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t.plain_text().len()), + _ => None, + }) + .sum() +} + +/// The frame of the story of text `id` that holds the character at byte `at` of the story's text, +/// and that character's byte in the frame; `None` unless that character is `c`. +fn story_place(doc: &vectorcraft_doc::Document, id: NodeId, at: usize, c: char) -> Option<(NodeId, usize)> { + let mut start = 0; + for f in doc.story_of(id) { + let Some(NodeKind::Text(t)) = doc.node(f).map(|n| &n.kind) else { continue }; + let text = t.plain_text(); + if at < start + text.len() { + return text.get(at - start..)?.starts_with(c).then_some((f, at - start)); + } + start += text.len(); + } + None +} + +/// The edits of [`put_alternate`] on a copy of the active document in a session of its own: `edit` +/// (`text.editRange`) puts `c` in at byte `at` of the story of text `id` (in whichever frame the +/// text flows it to), and glyph `picked` of `face` goes on it. The error of the step that fails; an +/// error too when the character is not where the edit put it. +fn try_on_a_copy( + app: &VectorcraftApp, + face: &vectorcraft_text::FontFace, + c: char, + picked: u32, + (id, at): (NodeId, usize), + edit: &serde_json::Value, +) -> Result<(), String> { + let Some(st) = app.session.active() else { return Ok(()) }; + let mut copy = vectorcraft_engine::Session::new(); + copy.add_document(vectorcraft_doc::Document::clone(&st.doc), None); + copy.execute("text.editRange", edit).map_err(|e| e.to_string())?; + let n = c.len_utf8(); + let doc = copy.active().map(|s| &s.doc); + let step = match doc.and_then(|d| story_place(d, id, at, c).and_then(|(f, byte)| Some((f, byte, d.node(f)?)))) { + Some((f, byte, node)) => match &node.kind { + NodeKind::Text(text) => style_at(text, byte).and_then(|style| { + alternate_command(f, (byte, byte + n), &style.features, style.glyph_alternate.is_some(), pick_for(text, byte, face, picked)) + }), + _ => return Err("Select text or click into text with the Type tool to insert glyphs".into()), + }, + None => return Err("Select text or click into text with the Type tool to insert glyphs".into()), + }; + if let Some((cmd, params)) = step { + copy.execute(cmd, ¶ms).map_err(|e| e.to_string())?; + } + Ok(()) +} + +/// Draw the Type tool's selected character, `c` (a range's first character, else the one before +/// the caret), with glyph `picked` of `face`: through the OpenType feature that draws that glyph +/// on it in its word when one does, else as a glyph choice ([`apply_alternate`]). Whether it +/// worked; nothing changes when the character already has that glyph. +fn draw_selected_with(app: &mut VectorcraftApp, face: &vectorcraft_text::FontFace, c: char, picked: u32) -> bool { + let Some(t) = selected_target(app).filter(|t| t.ch == c) else { return false }; + let (id, byte, features, has_choice) = (t.id, t.byte, t.style.features.clone(), t.style.glyph_alternate.is_some()); + let pick = match app.session.active().and_then(|s| s.doc.node(id)).map(|node| &node.kind) { + Some(NodeKind::Text(text)) => pick_for(text, byte, face, picked), + _ => Pick::Glyph(picked), + }; + super::character::end_typing(app); + apply_alternate(app, id, (byte, byte + c.len_utf8()), &features, has_choice, pick) +} + +/// How glyph `picked` of `face` goes on the character at `byte` of `text`: the OpenType feature +/// that draws it there in its word, the default glyph, else a glyph choice. +fn pick_for(text: &vectorcraft_text::TextObject, byte: usize, face: &vectorcraft_text::FontFace, picked: u32) -> Pick { + match vectorcraft_text::alternates_in_context(FontDb::global(), text, byte).filter(|f| f.font_id == face.id()) { + Some(f) if f.default == picked => Pick::Default, + Some(f) => f.alternates.iter().find(|x| x.gid == picked).and_then(|x| x.apply.clone()).map_or(Pick::Glyph(picked), Pick::Feature), + None => Pick::Glyph(picked), + } +} + +/// The style of the character at `byte` of `text`. +fn style_at(text: &vectorcraft_text::TextObject, byte: usize) -> Option<&CharStyle> { + let mut start = 0; + text.runs + .iter() + .find(|run| { + let end = start + run.text.len(); + let found = (start..end).contains(&byte); + start = end; + found + }) + .map(|run| &run.style) +} + /// The tooltip of a glyph no character maps (Show › Entire Font): its name from the font, `gid N` /// when it has none, its id, and the feature that gives it, if one does. fn unencoded_tip(face: &vectorcraft_text::FontFace, gid: u32) -> String { @@ -1709,6 +2057,409 @@ mod tests { } } + /// The corner triangles of the grid cells whose glyph has alternates: right-angled, with the + /// right angle at the cell's lower right corner. + fn corner_triangles(shapes: &[Shape]) -> Vec { + fn walk(s: &Shape, out: &mut Vec) { + match s { + Shape::Path(p) if p.points.len() == 3 && p.points[0].x == p.points[1].x && p.points[1].y == p.points[2].y => { + out.push(Rect::from_points(&p.points)); + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut out = vec![]; + shapes.iter().for_each(|s| walk(s, &mut out)); + out + } + + /// The Type tool editing `text` set in the alternates test font, the panel on Basic Latin, and + /// the egui context it is drawn in. + fn basic_latin_of_the_alternates_font(text: &str) -> (VectorcraftApp, serde_json::Value, egui::Context) { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let (mut app, id) = editing(text); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + (app, id, ctx) + } + + /// Click the one corner triangle of the grid, and return the glyph cells of the pop-up it + /// opens (drawn after the panel, on top of it). + fn open_corner_popup(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec { + let before = squares(&shapes(ctx, app, vec![])); + let corners = corner_triangles(&shapes(ctx, app, vec![])); + assert_eq!(corners.len(), 1, "only a has alternates among Basic Latin: {corners:?}"); + click(ctx, app, corners[0].center() + vec2(1.0, 1.0)); + let after = squares(&shapes(ctx, app, vec![])); + assert!(after.len() > before.len(), "the pop-up drew its glyphs: {} then {}", before.len(), after.len()); + after[after.len() - (after.len() - before.len())..].to_vec() + } + + /// A cell whose glyph has alternates has a corner triangle; a click on it opens a pop-up of the + /// glyph and its alternates in the font's order, and picking an alternate inserts the + /// character at the caret drawn with it, as one undo step. + #[test] + fn a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one() { + use vectorcraft_text::test_fonts::{alternates_family, unencoded_glyphs}; + let [u1, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xy"); + let face = FontDb::global().face(alternates_family(true), "Regular").expect("the test face"); + let a = face.glyph_for('a'); + assert!(face.has_alternates(a)); + let drawn = shapes(&ctx, &mut app, vec![]); + let (cells, triangle) = (squares(&drawn), corner_triangles(&drawn)); + assert_eq!(triangle.len(), 1); + assert!( + cells.iter().any(|c| c.contains(triangle[0].center()) && (c.max - triangle[0].max).length() < 2.0), + "in a cell's lower right corner: {triangle:?} among {cells:?}" + ); + select(&mut app, 1, 1); + let popup = open_corner_popup(&ctx, &mut app); + assert_eq!(popup.len(), 7, "a and its six alternates"); + let plain = glyph_ids(&app, &id); + let undo = app.session.active().unwrap().history.undo.len(); + // a, u1, b, u2: the fourth cell is ss01's u2. + click(&ctx, &mut app, popup[3].center()); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[1]], "the inserted a is drawn with the pick"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&app, &id), plain, "undo takes the character back out"); + // The cell's own glyph inserts the plain character, as a double-click does. + select(&mut app, 1, 1); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[0].center()); + assert_eq!(glyph_ids(&app, &id), [plain[0], a, plain[1]]); + // An alternate with no feature that draws it here (u1 is listed by aalt) still goes on. + select(&mut app, 2, 2); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(glyph_ids(&app, &id), [plain[0], a, u1, plain[1]], "status: {}", app.ui.status); + } + + /// With the Type tool's selection exactly the cell's character, a pick draws that character + /// with the glyph and keeps the text; picking the glyph it already has adds no undo step. + /// Without the Type tool, and with text in another font, the status says why and nothing + /// changes. + #[test] + fn a_pick_replaces_the_selected_character_and_says_why_when_it_cannot() { + use vectorcraft_text::test_fonts::{alternates_family, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xay"); + let plain = glyph_ids(&app, &id); + select(&mut app, 1, 2); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "the selected a stays: status {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[2]]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + select(&mut app, 1, 2); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the glyph it already has changes nothing"); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[2]]); + + // Text set in another font than the one the panel browses. + let family = alternates_family(true); + set_pstate(&ctx, "gl-font", Some((family.to_string(), "Regular".to_string()))); + app.run("text.setRangeStyle", json!({"id": id, "font": vectorcraft_text::FALLBACK_FAMILY})).unwrap(); + select(&mut app, 3, 3); + let undo = app.session.active().unwrap().history.undo.len(); + let before = glyph_ids(&app, &id); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(glyph_ids(&app, &id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.ui.status.contains("not of the font the selected text is set in"), "{}", app.ui.status); + + // No Type tool caret. + app.session.select_tool("select", Default::default()).unwrap(); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(glyph_ids(&app, &id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "Select text or click into text with the Type tool to insert glyphs"); + } + + /// A pick the inserted character cannot be drawn with (All Caps keeps a glyph choice from + /// being drawn) takes the character back out and keeps the status that says why: on its own, + /// and inside an undo group that is already open, which stays open with its earlier edit and + /// takes a pick that can be drawn in place of the selection. + #[test] + fn a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was() { + let [_, u2, ..] = vectorcraft_text::test_fonts::unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xy"); + let text = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + app.run("text.setFormat", json!({"ids": [id], "allCaps": true})).unwrap(); + // A step to redo, which the failed pick keeps. + app.run("text.setFormat", json!({"ids": [id], "underline": true})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + select(&mut app, 1, 1); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step is left"); + assert_eq!(app.session.active().unwrap().history.redo.len(), 1, "the redo step stays"); + assert!(!app.ui.status.is_empty(), "the status says why"); + + // In an open group with no edit yet, the failed pick leaves the group with nothing to undo. + app.run("edit.undoGroup.begin", json!({})).unwrap(); + select(&mut app, 0, 1); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy"); + assert!(!app.ui.status.is_empty(), "the status says why"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the empty group adds no step"); + + app.run("edit.undoGroup.begin", json!({})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "underline": true})).unwrap(); + select(&mut app, 0, 1); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy", "the replaced x is back: status {}", app.ui.status); + assert!(!app.ui.status.is_empty(), "the status says why"); + assert!(app.session.active().unwrap().undo_group.is_some(), "the group stays open"); + // A pick that can be drawn replaces the selection inside the group. + app.run("text.setFormat", json!({"ids": [id], "allCaps": false})).unwrap(); + select(&mut app, 0, 1); + let plain = glyph_ids(&app, &id); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(text(&app), "ay", "status {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [u2, plain[1]]); + assert!(app.session.active().unwrap().undo_group.is_some(), "the group stays open"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the group is one step"); + } + + /// After Select All in a threaded story, a pick replaces the whole story's text, as typing + /// does: the character drawn with the glyph stays, in one undo step. + #[test] + fn a_pick_replaces_a_threaded_story_that_select_all_selected() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "a bad cab ".repeat(30); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b, c] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_story(&app).map(|s| s.len()), Some(3), "the whole story is selected"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + let texts: String = [a, b, c].iter().map(|id| plain(&app, *id)).collect(); + assert_eq!(texts, "a", "status: {}", app.ui.status); + let first = [a, b, c].into_iter().find(|id| !plain(&app, *id).is_empty()).expect("a frame with the character"); + assert_eq!(glyph_ids(&app, &json!(first)), [u2]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + + /// After Select All in a threaded story whose first frame holds only the picked character, a + /// pick still replaces the whole story's text: the other frames' text goes too. + #[test] + fn a_pick_replaces_a_threaded_story_whose_first_frame_holds_one_character() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + // The first frame is wide enough for the "a" only; the ideographs flow on to the second. + let area = json!({"x": 10, "y": 10, "text": "a中中中", "size": 12, "area": {"width": 16, "height": 16}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + assert_eq!((plain(&app, a), plain(&app, b)), ("a".to_string(), "中中中".to_string())); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_editing(&app), Some((NodeId(a), 0, 1)), "the selection is the one character"); + assert_eq!(super::super::character::text_story(&app).map(|s| s.len()), Some(2), "the whole story is selected"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let texts: String = [a, b].iter().map(|id| plain(&app, *id)).collect(); + assert_eq!(texts, "a", "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &json!(a)), [u2]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + + /// A pick at the caret at the end of a full frame of threaded text puts the character in, and + /// the text flows it on to the next frame: it is drawn with the glyph there, and the Type tool + /// edits that frame with the caret after it. + #[test] + fn a_pick_at_the_end_of_a_full_frame_follows_the_character_to_the_next_frame() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let face = FontDb::global().face(alternates_family(true), "Regular").expect("the test face"); + let gid = |c| face.chars().into_iter().find(|(x, _)| *x == c).map(|(_, g)| g).expect("a glyph"); + let pt = |c| face.advance(gid(c)) * 12.0 / face.units_per_em(); + // The first frame holds the line "a xx " and not the next word. Every character is in the + // test font, so no fallback face measures the line. + let width = pt('a') + 2.0 * pt(' ') + 2.0 * pt('x') + pt('x') / 2.0; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "a xx xx", "size": 12, "area": {"width": width, "height": 16}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + assert_eq!((plain(&app, a), plain(&app, b)), ("a xx ".to_string(), "xx".to_string())); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + let end = "a xx ".len(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": end, "caret": end})); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!((plain(&app, a), plain(&app, b)), ("a xx ".to_string(), "axx".to_string()), "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &json!(b))[0], u2); + assert_eq!(super::super::character::text_editing(&app), Some((NodeId(b), 1, 1)), "the caret is after the character"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + + /// A pick on the selected last character of a full frame of threaded text, with a glyph wider + /// than the one it had, flows the character on to the next frame: the Type tool edits that + /// frame with the character still selected. + #[test] + fn a_wider_pick_on_the_selected_character_moves_the_selection_with_it() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let face = FontDb::global().face(alternates_family(true), "Regular").expect("the test face"); + let gid = |c| face.chars().into_iter().find(|(x, _)| *x == c).map(|(_, g)| g).expect("a glyph"); + let plain_a = gid('a'); + // The pop-up's glyphs in its order: the cell's own glyph, then the alternates. + let mut list = vec![plain_a]; + for alt in face.alternates('a') { + if !list.contains(&alt.gid) { + list.push(alt.gid); + } + } + let (index, wide) = + list.iter().copied().enumerate().max_by(|x, y| face.advance(x.1).total_cmp(&face.advance(y.1))).expect("the pop-up lists glyphs"); + assert!(face.advance(wide) > face.advance(plain_a), "an alternate wider than the a"); + // The first frame holds "x a" with the plain a, and not with the wider glyph. + let pt = |g: u32| face.advance(g) * 12.0 / face.units_per_em(); + let width = pt(gid('x')) + pt(gid(' ')) + (pt(plain_a) + pt(wide)) / 2.0; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let area = json!({"x": 10, "y": 10, "text": "x a", "size": 12, "area": {"width": width, "height": 16}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + assert_eq!((plain(&app, a), plain(&app, b)), ("x a".to_string(), String::new())); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 2, "caret": 3})); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[index].center()); + assert_eq!((plain(&app, a), plain(&app, b)), ("x ".to_string(), "a".to_string()), "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &json!(b)), [wide]); + assert_eq!(super::super::character::text_editing(&app), Some((NodeId(b), 0, 1)), "the character stays selected"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + + /// In Entire Font, a glyph no character maps whose substitutions give other glyphs has the + /// corner triangle too: its pop-up lists it and those glyphs, and a pick goes on the selected + /// character as a double-click on that glyph's cell would put it. + #[test] + fn an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + let ctx = egui::Context::default(); + choose(&ctx, &mut app, "Entire Font"); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let medial = g('u'); + assert!(face.unencoded_glyphs().contains(&medial) && face.has_alternates(medial), "the medial teh is unencoded and has alternates"); + // A screen tall enough for every cell of the font. + let run = |ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 200_000.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes.into_iter().map(|c| c.shape).collect::>() + }; + let click_at = |ctx: &egui::Context, app: &mut VectorcraftApp, at: Pos2| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(ctx, app, vec![egui::Event::PointerMoved(at), button(true)]); + run(ctx, app, vec![button(false)]); + }; + let drawn = run(&ctx, &mut app, vec![]); + let (cells, corners) = (squares(&drawn), corner_triangles(&drawn)); + let chars = face.chars().into_iter().filter(|(c, _)| !c.is_control() && !c.is_whitespace()).count(); + let unencoded = face.unencoded_glyphs(); + assert_eq!(cells.len(), chars + unencoded.len(), "every glyph has a cell"); + let cell = cells[chars + unencoded.iter().position(|g| *g == medial).expect("an unencoded glyph")]; + let corner = corners.iter().find(|t| cell.contains(t.center())).expect("its corner triangle"); + let undo = app.session.active().unwrap().history.undo.len(); + click_at(&ctx, &mut app, corner.center() + vec2(1.0, 1.0)); + let after = squares(&run(&ctx, &mut app, vec![])); + let popup = &after[cells.len()..]; + assert_eq!(popup.len(), 4, "the medial teh and its three alternates"); + click_at(&ctx, &mut app, popup[2].center()); + assert_eq!(glyph_ids(&app, &id), [g('B'), g('x'), g('M')], "status: {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// Show › Entire Font also lists the glyphs no character maps. #[test] fn entire_font_lists_the_unencoded_glyphs() { diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 3141cfb3c6..08aa580d56 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -764,9 +764,11 @@ pub fn image_summary(i: &Value) -> (String, String) { /// The Control bar for the one selected image: Linked File or Embedded, its file name, colour mode /// and effective resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask, -/// Crop Image and Remove Background. Whether one image is selected. A file name the row has no room -/// for is left out alone; after it, each control shows only while the row has room for it and -/// `reserve` after it, and the controls after one left out are left out too. +/// Crop Image and Remove Background. While the Crop Image tool is in use, the bar shows the file +/// name, colour mode and resolution only, and the tool's cropping options follow them. Whether one +/// image is selected. A file name the row has no room for is left out alone; after it, each control +/// shows only while the row has room for it and `reserve` after it, and the controls after one left +/// out are left out too. pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: f32) -> bool { let Some(i) = selected_image_info(app) else { return false }; let (name, details) = image_summary(i); @@ -786,6 +788,9 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui, reserve: ui.label(details); } fit.separator(ui); + if app.session.tool_id() == vectorcraft_tools::cropimage::ID { + return true; + } link_buttons(app, ui, id, linked, &name, LinkButtons::Fit(&mut fit)); // The Image Trace button grows past its usual width for a longer translated label. let arrow = widgets::SPLIT_ARROW; diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index d102c40d7e..6329f489b1 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -223,9 +223,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { if crate::shortcut_editor::is_recording(app) { return; } - // Escape closes a dropdown list or popover open in the dialog (each closes itself on it) and - // leaves the dialog open. - let popup = app.ui.dialog.as_ref().is_some_and(|d| { + // Escape closes a dropdown list or popover open in the dialog, or the palette's Recent + // Commands list (each closes itself on it), and leaves the dialog or the palette open. + let popup = app.ui.dialog.as_ref().map_or(crate::palette::recent_list_open(ctx), |d| { egui::Popup::is_any_open(ctx) || crate::dialogs::brush_options::tips_open(d) || crate::dialogs::new_document_popup_open(d) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 10ed4efa13..3e07419bb4 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -296,11 +296,11 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// Smooth and Simplify, Offset Path, the Object › Transform dialogs, Average, Split Into Grid, /// Vector Halftone, Rearrange All Artboards, Pathfinder Options, the Object › Plug-ins dialogs /// (Arrange in Grid, Replace with Top Object, the size, opacity and sort dialogs of the Arrange -/// add-on, Set Corners…, Divide into Dashes, Find Nearest Swatch, the swatch legend, the type +/// add-on, Set Corners…, Divide into Dashes, Tangent Circle…, Find Nearest Swatch, the swatch legend, the type /// tools, the select add-on and Select by Link Status…), three "…" items whose menu entry gives /// params, Smart Punctuation…, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset /// dialogs and Apply SVG Filter…. -const MENU_DIALOG_COMMANDS: [&str; 39] = [ +const MENU_DIALOG_COMMANDS: [&str; 40] = [ "object.path.smooth", "object.path.simplify", "object.path.offsetPath", @@ -323,6 +323,7 @@ const MENU_DIALOG_COMMANDS: [&str; 39] = [ "addon.arrange.sort", crate::addons::pathtools::set_corners::COMMAND, crate::addons::pathtools::dashes::COMMAND, + crate::addons::pathtools::tangent_circle::COMMAND, crate::addons::color::nearest::COMMAND, crate::addons::color::legend::COMMAND, crate::addons::typetools::COMMAND, diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2fbe54d633..d3698aaeef 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -692,6 +692,9 @@ pub struct UiState { /// Type → Recent Fonts, most recent first. #[serde(default)] pub recent_fonts: Vec, + /// Help › Search Commands' Recent Commands list: the ids of the last picks, most recent first. + #[serde(default)] + pub recent_commands: Vec, /// Families starred in the font menus (the ★ filter shows only these). #[serde(default)] pub favorite_fonts: Vec, @@ -1228,6 +1231,7 @@ impl Default for UiState { workspace_changes: vec![], recent_files: vec![], recent_fonts: vec![], + recent_commands: vec![], favorite_fonts: vec![], engine_prefs: Value::Null, color_guide: Default::default(), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index c4da70d84f..c8cbd94cfd 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -543,35 +543,80 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) /// The width of Mirror & Cut's Axis and Keep menus in the Control bar. const MIRROR_DROPDOWN_WIDTH: f32 = 96.0; -/// Crop Image's box: its centre (X, Y) and size (W, H) in the general unit, set through the tool's -/// `rect` option, then Apply (Enter) and Cancel (Escape), each while the row has room for it and -/// `reserve` after it. +/// Crop Image's cropping options: the cropped image's resolution (PPI: a list, with the +/// resolutions above what the image allows disabled, or a typed value), the reference point, the +/// box's X and Y (that point) and size (W, H) in the general unit with the link that keeps their +/// proportions, all set through the tool's options; then Apply (Enter) and Cancel (Escape), each +/// while the row has room for it and `reserve` after it. fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { - let set = app.session.tool_options()["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::>()[..] { + use vectorcraft_tools::cropimage::{self as crop, PPI_CHOICES}; + let opts = app.session.tool_options(); + let set = opts["rect"].as_array().and_then(|v| match v.iter().filter_map(Value::as_f64).collect::>()[..] { [x, y, w, h] => Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h)), _ => None, }); - let Some((_, _, r)) = app.session.active().and_then(|st| vectorcraft_tools::cropimage::crop_box(&st.doc, &st.selection, set)) else { return }; + let Some((r, image, own, max)) = app.session.active().and_then(|st| { + let (id, image, r) = crop::crop_box(&st.doc, &st.selection, set)?; + let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id)?.kind else { return None }; + let (own, max) = crop::image_ppi(im); + Some((r, image, own, max.min(2400.0))) + }) else { + return; + }; + let reference = opts["reference"].as_u64().filter(|v| *v <= 8).map_or(crop::CENTER, |v| v as usize); + let linked = opts["linked"].as_bool().unwrap_or(false); let t = Tokens::get(ui.ctx()); - let units = app.session.general_unit(); - let c = r.center(); + let set_option = |app: &mut VectorcraftApp, key: &str, value: Value| { + app.run("tool.setOption", json!({ "key": key, "value": value })).ok(); + }; + // Resolution: the list's choices above the image's limit are disabled; a typed value is held to it. + let ppi = opts["ppi"].as_f64().unwrap_or(own); + let label = |v: f64| crate::i18n::fill_once(tl!("{n} ppi"), &[("n", &format!("{}", (v * 100.0).round() / 100.0))]); + let labels: Vec = PPI_CHOICES.iter().map(|v| label(*v)).collect(); + let names: Vec<&str> = labels.iter().map(String::as_str).collect(); let mut fit = crate::chrome::Fit::new(reserve); - for (k, lbl, v) in [("x", "X:", c.x), ("y", "Y:", c.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { + let text = egui::RichText::new(tl!("PPI")).size(12.0).color(t.text_dim); + if fit.room(ui, &[widgets::text_width(ui, text.clone()), 80.0, 56.0]) { + widgets::field_label(ui, text); + let current = label(ppi); + if let Some(v) = + widgets::dropdown_with(ui, ("cb-crop", "ppi-list"), ¤t, &names, 80.0, |i| PPI_CHOICES.get(i).is_some_and(|v| *v <= max + 1e-6)) + .and_then(|i| PPI_CHOICES.get(i)) + { + set_option(app, "ppi", json!(v)); + } + // An image's own resolution above the limit (a linked image's, or one past 2400 ppi) still + // shows as it is; an edit there sets at most the limit. + if let Some(v) = widgets::range_field(ui, ("cb-crop", "ppi"), ppi, 1.0..=max.max(ppi).max(1.0), "", 2, 56.0) { + set_option(app, "ppi", json!(v.min(max.max(1.0)))); + } + } + fit.separator(ui); + // The reference point locator is 23 pt square. + if fit.room(ui, &[23.0]) + && let Some(i) = widgets::reference_point(ui, reference) + { + set_option(app, "reference", json!(i)); + } + let units = app.session.general_unit(); + let p = vectorcraft_geom::reference_point(r, reference); + for (k, lbl, v) in [("x", "X:", p.x), ("y", "Y:", p.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { let text = egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim); - if !fit.room(ui, &[widgets::text_width(ui, text.clone()), 80.0]) { + let widths = + if k == "height" { vec![22.0, widgets::text_width(ui, text.clone()), 80.0] } else { vec![widgets::text_width(ui, text.clone()), 80.0] }; + if !fit.room(ui, &widths) { break; } + if k == "height" + && widgets::icon_button(ui, if linked { "link" } else { "unlink" }, tl!("Constrain Width and Height Proportions"), linked, 22.0).clicked() + { + set_option(app, "linked", json!(!linked)); + } widgets::field_label(ui, text); - if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) { - let (mut c, mut w, mut h) = (c, r.width(), r.height()); - match k { - "x" => c.x = nv, - "y" => c.y = nv, - "width" => w = nv.max(0.0), - _ => h = nv.max(0.0), - } - let rect = [c.x - w / 2.0, c.y - h / 2.0, w, h]; - app.run("tool.setOption", json!({ "key": "rect", "value": rect })).ok(); + if let Some(nv) = widgets::num_field(ui, ("cb-crop", k), Some(v), units, 80.0) + && let Some(b) = crop::edited_box(r, image, reference, linked, k, nv) + { + set_option(app, "rect", json!([b.x0, b.y0, b.width(), b.height()])); } } fit.separator(ui); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 76ad9628d1..14c0398738 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -867,8 +867,8 @@ writes the HTML page to a temporary folder and opens it in the default browser ( PSD Options: Export As… with the PSD format (`file.exportAs {format: "psd"}`, then the save dialog) opens `psdOptions`: the raster rows of PNG Options (`ppi`, `background`, `antiAlias`), then `colorModel` (`rgb`, `cmyk`, `gray`; a CMYK document starts on `cmyk`), `layers` (true: Write Layers; false: Flat Image, whose background list starts at White), -`maxEditability` and `hiddenLayers` (with layers) and `embedIcc`. `ui.dialog.set` the fields and `ui.dialog.confirm` -writes the file(s) with `document.export`. +`preserveText`, `maxEditability` and `hiddenLayers` (with layers) and `embedIcc`. `ui.dialog.set` the fields and +`ui.dialog.confirm` writes the file(s) with `document.export`; with Flat Image it leaves `preserveText` out. Print: File → Print… (`file.print` with no params, Ctrl/Cmd+P) opens the `print` dialog on the document's print settings. Its fields are the `print.setup` settings (`copies`, `artboards`, `range`, `media`, `orientation`, diff --git a/docs/effects-parity.md b/docs/effects-parity.md index ff06ba5b69..b4d2fd447d 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -178,7 +178,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Item | Ours | |---|---| -| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | +| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, wrapped around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); no base materials, graphics on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b5ab18e9ae..9c46a01f77 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -296,7 +296,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | -| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | +| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | diff --git a/docs/mcp.md b/docs/mcp.md index cec550a8b9..2270997c85 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -264,6 +264,9 @@ the suite) keep the agent to the folders you give it: selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked. +- With `preserveEditing`, the document an SVG or SVGZ of these outputs carries leaves out the Export for Screens + folder (`export_settings.folder`) when it is outside the read roots, as `document.exportSettings` does; the + other export settings and the art are kept, and the open document keeps the folder. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` @@ -835,6 +838,20 @@ look was edited keep their look. Read as a source, by `graphicStyle.new`, `graph style link of its own gives the look and the style link of the topmost path directly in it, and a move with `appearance.transfer` clears each of those paths; a series group that has one of them is read itself. +The commands in the paragraph above read a graph's Axes group and Legend group, given by id or selected with Group +Selection, as they read a series group: the Axes group stands for the axis lines, tick marks, radar rings and labels +directly in it, and the Legend group for the legend labels directly in it. The graph stores what they set for every +line and label of each kind, as described below for a line or label given itself, and the groups keep no rows of their +own. An Axes or Legend group that has a fill or stroke row of its own, or holds no line or label, is edited itself, +except by `graphicStyle.redefine`, which passes the style to the lines and labels of a linked group whatever the group +holds. An `index`, `indices` or fill or stroke `item` given an Axes or Legend group whose lines and labels have +different rows, as the lines and labels of a new graph do, is an error unless `aligned` is true, which makes it a row +of the stack of the backmost line or label in the group, and `appearance.moveItem` does not move the rows of such a +group. With `aligned`, the graph stores the rows of only the lines and labels that have that row; a kind of label none +of whose labels has it keeps what it stored before. The graph keeps no graphic style link on its lines and +labels: they keep the look of a style applied to them, and are unlinked when the graph is drawn again. The commands +find these groups by their names, so a renamed Axes or Legend group is edited itself. + `transparency.set` and `object.setProps` with an opacity, blend mode, isolation, knockout or knockout shape for the object, given a series group's id or the selected series group, set them on the group itself, and the graph stores them for that series. The series group has them again when the graph is drawn again, and they apply to the group as a whole @@ -843,10 +860,12 @@ in addition to each path's own opacity and blend mode. `addon.arrange.randomizeO what they change on the group the same way. Each of the commands above that clears the group's own opacity, blend mode, isolation and knockout also removes what the graph stores for it. -The other commands given a series group's id edit the group itself, and the graph does not store what they set on it: -the `effect.*` commands and `appearance.addEffect`, and the paint, stroke and gradient commands with a fill or stroke -`item`, which is a row of the group's own stack. The Appearance panel and `appearance.setActiveItem` read the selected -group's own rows. +The other commands given a series group's id, or a graph's Axes or Legend group, edit the group itself, and the graph +does not store what they set on it: the `effect.*` commands and `appearance.addEffect`, and the paint, stroke and +gradient commands with a fill or stroke `item`, which is a row of the group's own stack. `transparency.set` and +`object.setProps` with an opacity or blend mode for the object, given an Axes or Legend group, edit the group itself the +same way. `paint.setFill`, `paint.setStroke` and the recolor commands given the Axes group store the line rows, as +described below. The Appearance panel and `appearance.setActiveItem` read the selected group's own rows. When a graph is drawn again (a change to its data, its type, or its column or marker designs), it draws the art of a column or marker design in a series again from the design, and an edit made to that art is lost. The art is any object @@ -909,9 +928,11 @@ placement they set there. A stroke weight and dashes are stored as the label sho scaled. When the characters of labels of one kind change differently, the frontmost label sets what the kind keeps. On a pie with Legends in Wedges, a fill a command sets on the legend labels is drawn on every wedge, black included, until that command is undone; a size, font or stroke change does not set one. Before that, their fill is stored only when -every legend label the command reaches ends up with the same fill. Otherwise they are drawn again in black, or white on -a dark wedge. These commands do not store the colors they give a graph's axis lines, ticks and radar rings, which are -drawn again with their default paint. +every legend label the command reaches ends up with the same fill. The recolor commands also need to be given the legend +labels themselves: a recolor given the graph or a group that holds it does not store their fill. When their fill is not +stored, they are drawn again in black, or white on a dark wedge. `paint.default` stores the black fill and no stroke for +the kind of each label it reaches, also when the label already showed them. What these commands change on a graph's +axis lines, tick marks and radar rings is stored as described below. `text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that @@ -935,11 +956,14 @@ The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, a transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its kind of label: the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order and their place relative to the Characters row, and the label's object opacity and blend mode. They store them even when the -label already showed them. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and +label already showed them, but an edit of a hidden row that leaves the topmost visible rows as they were, and an +`appearance.moveItem` of the Contents row that leaves them in place, store nothing. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and an `appearance.copyFrom` (Eyedropper) pick of transparency store only the label's object opacity and blend mode; -`appearance.copyFrom` with `append` stores the rows. When the graph is drawn again, every label of that kind gets what -is stored, with a placed gradient fitted to each label, and the graph saves it as `valuesRows`, `categoriesRows` and -`legendRows` in its label styles. Rows below the topmost one of each kind, a row's effects, other stroke options (caps, +`appearance.copyFrom` with `append` stores the rows of the kinds it adds (fill, stroke or both), and the object opacity +and blend mode only when it also applies the object's transparency. `graphicStyle.apply` with `add` stores the rows of +the kinds the style shows. Both leave a row of the other kind as the kind keeps it, and `graphicStyle.apply` with `add` +also leaves the object opacity and blend mode the kind keeps. When the graph is drawn again, every label of that kind gets what is stored, with a placed +gradient fitted to each label, and the graph saves it as `valuesRows`, `categoriesRows` and `legendRows` in its label styles. Rows below the topmost one of each kind, a row's effects, other stroke options (caps, joins, dashes) and effects applied with `effect.*` are not stored. When labels of one kind are edited together, the last one in the order of the targets (`ids` as given, otherwise paint order) sets what the kind keeps. `appearance.copyFrom` onto the whole text of a label also stores the character attributes it applies and, from type, @@ -947,6 +971,38 @@ the paragraph attributes. `paint.setFill` and `paint.setStroke` store a characte the label's characters (the whole label, or all of its text highlighted with the Type tool), and the row when it goes to a row. A stored character gradient also fits each label. +On a graph's axis lines and tick marks, and separately on a radar graph's rings, `paint.setFill`, `paint.setStroke`, +`addon.color.fillToStroke`, `addon.color.strokeToFill`, the stroke, gradient and recolor commands above, `paint.swap`, +`paint.default`, the `appearance.*` commands (`appearance.copyFrom`, the Eyedropper, included), `graphicStyle.apply`, +`graphicStyle.redefine`, `transparency.set` and `object.setProps` store what a line shows for every line of its kind: +the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order, and the line's object +opacity and blend mode. `paint.setFill`, `paint.setStroke` and the recolor commands also store them when given the +graph, its Axes group or a group that holds the graph, so the lines keep the paint those commands give a whole graph. +The other commands store them when given the line itself, and the `appearance.*` and graphic style commands and +`transparency.set` with an `item` also when given the Axes group, as described above. `transparency.set` without an +`item` and `object.setProps` store only the object opacity and blend mode. `appearance.clear`, `appearance.transfer`, +`graphicStyle.apply`, `graphicStyle.redefine`, and `appearance.copyFrom` with every attribute picked up and applied or +with `append`, store a line's rows even when the line already showed them; `graphicStyle.apply` with `add` and +`appearance.copyFrom` with `append` store only the kinds of row they add. `appearance.addFill` and +`appearance.addStroke` store the row they add when it becomes the line's topmost visible row of its kind, also when the +line already showed its paint, weight and opacity. The other commands, an `appearance.copyFrom` +of some attributes included, store only what they change on a line's rows; the kind keeps its other attributes, also +when the line still shows different ones until the graph is drawn again. `paint.setFill`, `paint.setStroke`, +`addon.color.fillToStroke` and `addon.color.strokeToFill` also store the paint they write on a line's topmost visible +fill or stroke row when the line already showed it. `appearance.setItem` and an `appearance.copyFrom` of some +attributes store the paint, stroke weight, and row opacity and blend mode they write to that row in the same way, and +`stroke.set` stores the weight it writes there. An `appearance.copyFrom` that does not apply +the object's transparency, and `graphicStyle.apply` with `add`, leave the object opacity and blend mode a kind keeps as +they are, also when the line still shows other ones. `paint.default` stores the default fill and stroke rows for a +line's kind even when the line already showed them, and leaves the object opacity and blend mode the kind keeps. Rows +equal to a kind's default stroke (0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved, and +an edit of a hidden row that leaves the topmost visible rows as they were stores nothing. When one command reaches +several lines of one kind, the frontmost line in +paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and +each line fits it when the graph is drawn again. The graph saves the rows as `axisRows` and `ringRows` in its label +styles. Other stroke options (caps, joins, miter limit, alignment, dashes and arrowheads), rows below the topmost one of +each kind, and effects are not stored, so a dash set on a line is drawn solid again. + `effect.apply {"effect": "path.outlineObject"}` (Effect › Path › Outline Object) takes no parameters. Type that carries it is drawn, exported and expanded as its glyph outlines and stays editable type, and the effects after it reshape those outlines. On paths, compound paths and images it does not change what is drawn. On an image's own fill or stroke @@ -1941,6 +1997,26 @@ and `rotate` in `object.transformEach`; `ppi` in `object.rasterize`; `width`, `h four numbers, such as a string, with `rect must be [x, y, width, height]`; a null `rect` crops to the artboard, as a missing one does. +`object.cropImage {ppi}` sets the cropped image's resolution in pixels per inch: the cut pixels are resampled to it, +and the image keeps the size of the crop box. A `rect` over the whole image with a new `ppi` only resamples the image. +An image scaled differently across and down is resampled on both sides, so its pixels come out square at `ppi`. +A turned or skewed image is drawn at the `ppi` given, even its own, and over the whole box around it as well; without +`ppi` it is drawn at the density of that box. The Crop Image tool's Apply sends such an image's own resolution when +no other is set and the image can be cropped to it, and crops it over the whole box only when a resolution is chosen. +The most it takes is the image's own resolution (along the denser side of its pixel grid, however it is turned), or +300 ppi for a linked image; above that it is refused with `ppi can't be more than {max} for this image`. A value +outside 1 to 2400 is refused with `ppi must be between 1 and 2400`, and a value that is not a positive number with +`ppi must be a positive number, not {ppi}`. A resample whose working copies would pass the raster allowance (2 GB, +512 MB in the web app) is refused with `an image of {w} × {h} pixels is too large to resample`, naming the size +of the pixels being resampled. A null `ppi` is read as a missing one, and `ppi` with +`trim` is refused. While the Crop Image tool is chosen, `tool.setOption` sets `ppi` (the resolution Apply sends), +`reference` (0 to 8, left to right and top to bottom: the point of the box that the Control bar's X and Y name and +that its W and H resize about; 4, the center, by default) and `linked` (W and H keep the box's proportions; false by +default). It refuses another value of those three, such as a `ppi` of `"high"`, a `ppi` above what the selected +image allows or a `reference` of 9, and changes nothing; a null `ppi` goes back to the image's own. `tool.options` reads them back with `rect`. +Apply holds a `ppi` set before the image was selected to that image's limit. With `linked` on, a new W or H that would +not fit the image is reduced with the other side in proportion, and the box slides back within the image. + `object.createObjectMosaic` (`columns`, `rows`), `object.transformEach` (`reference`, `seed`) and `artboard.rearrange` (`columns`) take whole numbers, written `4` or `4.0`. A fraction or a negative number is refused with `` `columns` must be a whole number ``. A string or another value that is not a number is refused with @@ -3459,7 +3535,7 @@ already walks Image Trace. Short agent entry points: `[x, y, pressure, tiltX, tiltY, rotation]` or `{x, y, pressure?, tiltX?, tiltY?, rotation?}`, with `null` for what a point lacks, and a `pointer_gesture` event takes `tiltX`, `tiltY` and `rotation`, which the Paintbrush records. `tiltX` and `tiltY` are degrees −90..90 in document axes, positive leaning right and leaning down the page (one - without the other is 0); `rotation` is the barrel's rotation in degrees clockwise. The stroke keeps how far the pen + without the other is 0); `rotation` is the barrel's rotation in degrees clockwise, 0..360. The stroke keeps how far the pen leaned (`tilt`, 0 upright to 1 lying flat), which way (`bearing`, degrees counter-clockwise from leaning right; a pen within 1° of upright takes the bearing before it, or at the start of the stroke its first one) and how far the barrel turned (`rotation`, degrees counter-clockwise). A point without a tilt that other points have counts as @@ -3879,16 +3955,20 @@ already walks Image Trace. Short agent entry points: black ring around a white disc around a black dot, black gets two groups. `layer.releaseToLayers` on the expanded group then gives each group a sublayer. A trace made with `autoGrouping` is refused. Expanding by color also refuses a trace with a live Pathfinder effect. - An Abutting trace with Fills (not Flat Logo) also holds a group named `Seam Fills` under its paths: for each color, a - stroke 1.5 image pixels wide (at the image's larger scale, when it is stretched more one way) with butt caps and round joins along the edges where a filled path of that color meets a - filled path drawn after it, in that color (a gradient path's stroke takes its gradient). Without it, a renderer that - anti-aliases each path on its own shows a light hairline along every shared edge. The traced paths and their shared - edges are the same with or without it, and edges against the image's border, a transparent area or a color left out - get no stroke. A trace whose paths have more than half of the trace's anchor limit (8,000,000, 2,000,000 on the web) - has no seam fills, so that paths and seam fills together stay within the limit. Both Expand commands keep the group, and `byColor` leaves it under every color's group. The strokes - are separate objects: after Expand, recoloring, moving or deleting a traced path leaves them as they are, and deleting - the group removes them. The reply's - `paths` and `anchors` count the traced paths only. + An Abutting trace with Fills (not Flat Logo) also holds a clip group named `Seam Fills` under its paths. For each + color it holds one stroke along the edges where a filled path of that color meets a filled path drawn after it, in + that color (a gradient path's stroke takes its gradient), with butt caps and round joins. The stroke is 1.5 image + pixels wide, VectorCraft's own width. On an image stretched more one way than another, the group holds each + stroke's outline in image pixels as a filled path instead; the outline covers 0.75 image pixels on each side of its + edge. The group clips the strokes or outlines to the image's box within the box of the traced paths, and its + bounds lie within that box. Where a shared edge ends at, or runs within 0.75 image pixels of, a + transparent area or a color left out, its stroke can reach up to 0.75 image pixels into that area. Paths that + became live shapes (`shapes`) take no part. The traced paths and their shared edges are the same with or without + the group. A trace whose paths have more than about half of the trace's anchor limit (8,000,000, + 2,000,000 on the web) has no seam fills. Both Expand commands keep the group, and `byColor` leaves it under every + color's group; `byColor` refuses a trace whose seam fills' group was moved above a path. The strokes are separate + objects, in a trace and after Expand: recoloring, moving or deleting a traced path leaves them as they are, and + deleting the group removes them. The reply's `paths` and `anchors` count the traced paths only. With `keepColors` in `params`, the reply's `warnings` name each listed color that no traced color matches, and say when nothing was traced. `noise` (Color, Grayscale and Black and White, not Flat Logo) merges areas smaller than that many pixels into a @@ -4218,9 +4298,12 @@ Parameters: `angle` (degrees, 0..360, default 360), `offset` (points, 0..100000, default 0), `ambient` (Ambient Light, 0..200%, default 25; an earlier `lightAzimuth` and `lightElevation` are read as the same light), `cap` (boolean, default true), and `expandVisibleOnly` (boolean, default true). A vertical-line profile needs a positive offset to have a radius. `cap` closes each circular endpoint of an open profile with one curved, uniformly shaded -vector path. Body faces share that curved rim. Partial sweeps use sectors and leave their angular -cut sides open. Closed or coincident-end profiles are unchanged. -Missing `cap` enables caps; set it to false for open endpoints. Shaded Revolve surfaces automatically interpolate curved-surface lighting with vector gradients while preserving profile corners and flat caps. There is no separate smoothing parameter. `shade: false` disables all lighting. Visibility of intersecting surfaces is approximate. +vector path. Body faces share that curved rim. Partial sweeps use sectors, and `cap` also closes their two +angular cut sides with flat faces: the region between each open subpath and the axis and the area the closed +subpaths fill together under the object's fill rule, one face for each region. A closed subpath that walls a hole +leaves that hole open, and an overlap of closed subpaths is filled or left open as the fill rule fills it. +Exported 3D meshes include the cut sides. +Missing `cap` enables caps; set it to false for open endpoints and open cut sides (hollow). Shaded Revolve surfaces automatically interpolate curved-surface lighting with vector gradients while preserving profile corners and flat caps. There is no separate smoothing parameter. `shade: false` disables all lighting. Visibility of intersecting surfaces is approximate. `lights` is null by default, retaining the earlier single-light controls. Set an array of one to ten objects to replace that light: `{color: "#rrggbb", intensity: 0..100, rotation: -180..180, height: 0..90, softness: 0..100, behind: bool}`. Defaults per light are white, 80%, 125.26 degrees, 30 degrees, 0%, false. Omitted fields use defaults; unknown nested keys and malformed lists are refused before mutation. `ambient` is shared and counted once. Set `lights: null` to restore the earlier controls. The list is saved in the native file and survives preview, undo and expansion. ```json @@ -4451,7 +4534,7 @@ an unknown surface or shading color is refused with an error and the document is `effect.apply {effect: "threeD.classicRevolve", params: {...}, ids?, item?}` is Effect › 3D and Materials › 3D (Classic) › Revolve (Classic)…. It sweeps the profile round a vertical axis as `threeD.revolve` does, at 64 segments for a full turn, and draws every face, back to front, with the classic surfaces. Parameters: `angle` (degrees, -0..360, default 360), `cap` (true closes the profile's open ends, false leaves the surface hollow), `offset` (points, +0..360, default 360), `cap` (true closes the profile's open ends and a partial sweep's cut sides, false leaves the surface hollow), `offset` (points, 0..1000, default 0; the axis's distance from the profile, so a value above 0 makes a ring), `edge` (`left`, the default, or `right`: the edge of the profile's bounds the axis is at), `rotationX/Y/Z` and `perspectiveAngle` as above, and `surface`, the lights, `ambient`, `highlightIntensity`, `highlightSize`, `blendSteps`, `shadingColor`, @@ -4578,7 +4661,10 @@ the others turn by the same hue). `limitTo` snaps new colours to a swatch librar new color as it is and shuffles only the rows that hold current colors. A row without `from`, or with a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An -empty row does not count toward Colors. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art +empty row does not count toward Colors. While it is empty, the dialog's Edit tab does not show it (its sliders edit +the base color when the empty row is selected), the harmony rules, +linked moves and the Color Theme Picker leave its new color as it is, and Save All Colors and a new color group saved +from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the @@ -4620,7 +4706,7 @@ objects are read. As VectorCraft's own rule, each object read weighs the same, s among its pixels; the vector art a symbol instance places counts as one object, and each image it places counts on its own), and similar colors merge (k-means in Lab) into at most `colors` (1 to 64, default 5), each shown by its most used color in its own model. Picks that touch no art return no colors. In the Recolor Artwork dialog the picks are the `themePicks` field: the rows that aren't -excluded take the palette as their new colors in row order, the colors repeating when the rows outnumber them. +excluded and hold current colors take the palette as their new colors in row order, the colors repeating when the rows outnumber them. ```json {"name":"run_command","arguments":{"command":"recolor.pickTheme","params":{"picks":[{"at":[120,80]},{"rect":[200,40,320,140]}],"colors":4}}} @@ -4646,7 +4732,7 @@ bar sits under the Edit tab's wheel: each row with a share is a part as wide as the largest first. Dragging the edge between two parts moves width between them, and when the drag ends the widths become the `weights` field, which moves the rows' current colors and previews the result. The New Color Group menu beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors -of the rows that are not excluded, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +of the rows that are not excluded and hold current colors, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. ```json {"name":"run_command","arguments":{"command":"recolor.weigh","params":{"map":[{"from":["rgb 255 0 0","rgb 128 0 204"],"to":"#00ff00"},{"from":["rgb 0 0 255"],"to":"#ffff00"}],"weights":[1,1]}}} @@ -5324,11 +5410,19 @@ the object with the image). Type with a geometry effect (Outline Object included is outlined; type that has no fills or strokes of its own and whose only effects are shadows or outer glows stays type, with the image under it. A group's or layer's own fills and strokes become objects among its members, and its members are expanded too. A symbol instance whose topmost fill or topmost stroke is visible, has an opacity above 0 -and has a geometry effect becomes a group of its art: that fill's effects reshape the filled shapes of the art and that -stroke's effects reshape its stroked shapes, which keep their colors, as the canvas draws them (VectorCraft's own -rule); the instance's other fills and strokes are dropped. A raster effect on that fill or stroke draws on the filled -or stroked shapes of the art, and expanding makes it an image as for other objects; with no geometry effect, the -instance stays an instance over a shadow or glow image, and a blur, feather or inner glow replaces it with the image. +and has a geometry or raster effect becomes a group of its art: that fill's effects reshape the filled shapes of the +art and that stroke's effects reshape its stroked shapes, which keep their colors, as the canvas draws them +(VectorCraft's own rule); the instance's other fills and strokes are dropped. A raster effect on that fill or stroke +draws on the filled or stroked shapes of the art, and expanding makes it an image as for other objects: a shadow or +glow image goes under the art, and a blur, feather or inner glow replaces the instance with the image. A symbol +instance in the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance +passes on, becomes its art and image the same way, and so do the instances in that art (VectorCraft's own rule). +Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster +effect on an instance in the art stayed live. +One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own +limits). An object or symbol instance whose image would go past them stays as it is, with its effects and the objects +in it; the result then carries a `warning` and `rasterLeft`, the number of objects left so, and when nothing else +expands the command fails with the same message. A legacy `.ai` save notes it the same way. The result is `{ids}`; when an image in the art can't be decoded, the images made from raster effects do not show it, and the result also carries the `warning` that Flatten Transparency gives. A path's strokes stay strokes, as the @@ -5799,11 +5893,24 @@ moves that point alone as the focal point, with or without Shift (Shift keeps th focal points stay highlighted where it left them; Escape during a drag puts the path back and keeps them, and switching to another tool clears them. +`path.freehand`, `brush.freehand`, `path.knife`, `path.eraseRegion`, `path.eraseSegments`, `path.smoothRegion`, +`path.joinScrub` and `path.blob` refuse a pen `pressure` outside 0 to 1, a `tiltX` or `tiltY` outside -90 to 90 and a +`rotation` outside 0 to 360 with an error such as `` `tiltX` must be from -90 to 90 ``, naming the key, and a point +given as an array of more than six numbers with `` `points[3]` must be an array of at most 6 entries ``, naming the +point. `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt with +`` `size` must be from 0.1 to 1000 `` and a `sizeVariation` over 1000 pt with +`` `sizeVariation` must be from 0 to 1000 ``, in every `sizeMode` and when it is left out. `path.blob` refuses a +negative `sizeVariation` with the same message, and `path.eraseRegion` with "sizeVariation must be 0 or more". The +document and the selection do not change and no undo step is recorded. A null is read as a key left out, and a point given as `[x, y]` +has no pen values. The pressure and tilt ranges are those of +[Pointer Events](https://www.w3.org/TR/pointerevents3/); the rotation, size and size variation ranges are +VectorCraft's own values. + `path.eraseRegion` (the Eraser) takes a variation mode for each of its tip's values, as the variation menus of Eraser Tool Options set them ([Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)): `angleMode` with `angleVariation` (degrees, 0 to 180), `roundnessMode` with `roundnessVariation` (percent, 0 to 100) -and `sizeMode` with `sizeVariation` (points, 0 or more), each `"fixed"` (the default), `"random"`, `"pressure"`, +and `sizeMode` with `sizeVariation` (points, 0 to 1000), each `"fixed"` (the default), `"random"`, `"pressure"`, `"tilt"`, `"bearing"` or `"rotation"`. A value that varies takes up to its variation either way. Random draws one value for the drag. Pressure goes from the value less the variation where the pen presses lightest to the value plus it where the pen presses hardest. Tilt goes from less with the pen lying flat to more with it upright. Bearing and @@ -8803,6 +8910,28 @@ appearance of their own or knockout stay one pixel layer. Hidden layers and obje `hiddenLayers: true` writes them as hidden layers. `layers: false` writes one flat image, on white where nothing is drawn. Files are at most 30000 pixels a side. +`preserveText: true` (with layers; refused with `layers: false`) writes horizontal and vertical point type as type +layers that a reader can edit: each holds the text, its fonts (by PostScript name), sizes, leading, tracking, scaling, +baseline shift, caps, underline, strikethrough, fill color, Fractional Widths, paragraph alignment, orientation and +anti-aliasing method (None with `antiAlias: none`), at the export's resolution, and keeps its pixels for readers that +show them. The font is the installed version the character style names, if any. VectorCraft writes only point type in +solid colors with whole-number tracking whose characters are all in their own font (none drawn with a fallback font), +that sets no other character attribute (no stroke, kerning, rotation, OpenType feature, small caps, position, East +Asian setting or language other than the default English: USA), whose paragraphs set nothing but their alignment +and line breaking (no indents, spacing, tabs, bullets or numbers, Auto Leading, word or letter spacing, Standard +composer, and no Mojikumi other than the default in type with Chinese, Japanese or Korean characters) and run left to right (set, or from their first strong +character), and that has no inline graphics, ruby, System Layout, Optical Margin Alignment, effects, appearance of its +own or opacity mask as a type layer; other type, area type and type on a path stay pixels. Without `maxEditability`, a +layer or sublayer that holds such type becomes a group of its type layers and one pixel layer for each stretch of art +between them, unless other art in it blends in a mode other than Normal: then the layer stays one pixel layer. Hidden +type counts only with `hiddenLayers`. With `maxEditability`, every object is a layer as above. The PSD Options dialog +has the option as Preserve Text Editability +(). + +```json +{"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"preserveText":true}}} +``` + PSD files (`.psd`, and `.psb`, the large document format) place as their merged image, the flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution. @@ -9469,13 +9598,23 @@ a spelling dictionary marks nothing. English words come from the first dictionar dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof. Words in capitals, words with digits and web addresses are taken as correct. The result is `{words: [{id, start, end, word, lang}], more}`: `start` and `end` are byte offsets in the type object's text, the -ones `text.editRange` takes, so `text.editRange {id, start, end, insert}` changes a word as one undo step. At most -10,000 words are listed; `more` is `true` when there were more. `text.spelling.suggest {word, max?, lang?}` gives -the words the dictionary of `lang` (default English) suggests instead of `word`, best first, at most `max` (1 to 20, -default 5). Both only read the document. +ones `text.editRange` takes, so `text.editRange {id, start, end, insert}` changes a word as one undo step, and +`text.spelling.change {to, words: [{id, start, end}…]}` changes every listed word to `to` as one undo step (Check +Spelling's Change All; an error, with nothing changed, when a word's bytes are not in its object's text or two words +overlap). A listed word that already reads as `to` is left alone; when every one does, the command makes no edit and +no undo step, and `changed` is 0. At most +`max` words are listed (1 to 10,000, default 10,000); `more` is `true` when there were more. To get the rest, check +again with `from: {id, byte}` set to the last word's `id` and `end`: that check lists the words of that type object +that start at `byte` or later, then those of the objects after it, so a type object with more unknown words than one +check lists is read to its end. `from.id` must be one of the objects checked. The paragraphs before the one that +holds `from.byte` are not checked again; that paragraph is checked whole. `text.spelling.suggest {word, max?, lang?}` +gives the words the dictionary of `lang` (default English) suggests instead of `word`, best first, at most `max` (1 to +20, default 5). `text.spelling.check` and `text.spelling.suggest` only read the document. ```json {"name":"run_command","arguments":{"command":"text.spelling.check","params":{}}} +{"name":"run_command","arguments":{"command":"text.spelling.check","params":{"from":{"id":12,"byte":340},"max":100}}} +{"name":"run_command","arguments":{"command":"text.spelling.change","params":{"to":"drawing","words":[{"id":12,"start":4,"end":10}]}}} {"name":"run_command","arguments":{"command":"text.spelling.suggest","params":{"word":"drawng","lang":"en"}}} ``` @@ -9904,9 +10043,19 @@ font based on the one picked, Delete Font takes it out, Import… adds the fonts picked. Custom shows the font's custom character sets: Character Set picks one, New adds a set based on the one picked, Delete Set takes it out, and Name renames it. Character › Direct Entry adds the characters typed, and Character › Unicode adds the characters of hexadecimal codes (`3042`, `U+3042`, several separated by spaces or commas); Add skips -characters the set already lists. Delete takes the character picked out of the set. OK runs `type.compositeFonts.set` -with every font as one undo step; a refused font keeps the dialog open. `ui.dialog.set` takes `custom`, `entry` and -`char` (the index of the character picked in the set) as soon as the dialog opens. +characters the set already lists. Delete takes the character picked out of the set. Show Sample (Hide Sample when it +shows) draws the font picked in a line of sample text, with the first character of each custom set added, and a button +beside it for each line it can mark: ICF Box, Em Box, Baseline, Cap Height, Max Ascent/Descent, Max Ascender and +x-height ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). +The em box and ICF box are those of the font of the part that sets the sample's first Kanji (the Kanji part, or a +custom set that holds that character), the cap height and x-height those of the face the Roman letters are drawn in (a fallback face when the part's font lacks the character), Max Ascent/Descent the highest +ascent and lowest descent of the faces the sample uses, and Max Ascender the top of its tallest glyph; each takes its +part's size, baseline and vertical scale. Zoom draws it at 25% to 800% of 36 pt. The +sample text, the zoom steps and the size are VectorCraft's own. OK runs `type.compositeFonts.set` with every font as one +undo step; a refused font keeps the dialog open. `ui.dialog.set` takes `custom`, `entry` and `char` (the index of the +character picked in the set) as soon as the dialog opens, and `sample` (true or false), `zoom` (25, 50, 75, 100, 200, +400 or 800) and `lineIcfBox`, `lineEmBox`, `lineBaseline`, `lineCapHeight`, `lineAscentDescent`, `lineAscender` and +`lineXHeight` (true or false; the first three start true); another value is refused. ```json {"name":"run_command","arguments":{"command":"type.compositeFonts.set","params":{"fonts":[{"name":"My Composite","parts":{"kanji":{"font":"Source Han Sans"},"roman":{"font":"Source Sans 3","size":95,"baseline":-2},"numerals":{"font":"Source Sans 3"}}}]}}} @@ -11010,9 +11159,23 @@ the fallback font and is listed as missing, without editing the document. The ty symbols and pattern swatches is laid out again too, and inline graphics take the new size of their symbols' art. The app does so by itself when its window comes to the front and a font folder changed meanwhile. +`text.similarFonts {family, limit?}` gives the families `text.fontList` lists in the order a font menu's Show Similar +Fonts lists them (the ≈ button on a family's row; the ≈ chip under the filters clears it): `{family, families}`, with +`family` the family's own name first, then the families that set the same script (Japanese, Thai or neither), then the +others, each group nearest first. The measure is VectorCraft's own. It compares each family's face nearest an upright +Regular by its OS/2 PANOSE digits (only between faces of the same PANOSE family kind), weight and width classes, x-height, +cap height and average character width, and its `post` italic angle (a named instance of a variable font takes its `wght` +and `slnt` settings), leaving out a number either face does not give, and counts a family of another kind (serif, sans +serif, script and the font menu's other kinds) as further away. It reads these when a font is cataloged or loaded and opens +no font file when asked. `limit` (a whole number from 1 to 100000) keeps +the first ones. A missing or blank `family` fails with `` `family` is required ``, one that is not a string with +`` `family` must be a string ``, a family that isn't available or that the font menus don't list with ``font family `` is not available``, and any +other `limit` with `` `limit` must be a whole number from 1 to 100000 ``. + ```json {"name":"run_command","arguments":{"command":"text.fontList","params":{}}} {"name":"run_command","arguments":{"command":"text.fontList","params":{"family":"Source Serif 4"}}} +{"name":"run_command","arguments":{"command":"text.similarFonts","params":{"family":"Source Sans 3","limit":10}}} {"name":"run_command","arguments":{"command":"text.rescanFonts","params":{}}} ``` @@ -12057,7 +12220,14 @@ Tools: screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has gone 3 screen pixels from the press, the gesture stays a drag even when it ends near the press. An Alt-drag draws a freehand line and runs it with `points` on release; a line of more than 65,536 points is dropped. Nothing changes - while dragging, and Escape during a drag removes nothing. The tool has no options. + while dragging, and Escape during a drag removes nothing. Hovering draws in red the stretch a click there would + remove. It draws nothing when a click would remove nothing, or when finding the path's crossings takes more than a + twentieth of the work a click may do. A drag draws in red every stretch its release would remove while it reaches at + most 32 paths, the paths it reaches times the paths that can be edited come to at most 10,000,000, and a freehand + line has at most 4,096 points; past those limits it draws none. Once finding the crossings takes more than a + twentieth of the work a release may do, or checking the line against the paths' segments takes more than 1,000,000 + box tests, the drag draws none until the next press. A click or a release still removes what it reaches. The tool + has no options. Commands: @@ -12113,6 +12283,26 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. +- `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths + and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so + `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` + defaults to the selection. A circle touches a shape when it meets the shape's outline without crossing it, the whole + outline lying outside the circle or inside it: at a smooth point it is tangent to the outline, and at a corner or an + open end it passes through that point. A compound path's members count as one outline. For shapes that are all + circles of four curved segments (as the Ellipse tool draws them) the answers come from the true circles and are then + moved onto the drawn Bézier outlines, which differ by up to 0.0273% of the radius; within that much of a tangency + threshold the true circles decide. Every circle that touches all the shapes is found (three circles have up to + eight); with three shapes, circles up to 64 times the diagonal of the box around the shapes' anchors and handles. + They are listed by radius, then top to bottom, then left to right, and `circle` (0 to 64; 0 by default) picks the + nth of them, or 0 draws them all. Each circle is a new ellipse with the current paint on top of the current layer, + or of the isolated group, and the circles are selected; inside an isolated compound path they join it. Locked and + hidden shapes given by `ids` are read and left as they are. It is an error, with the document unchanged, when no + circle touches the shapes, when more than 64 do (shapes touched along a whole curve, such as two concentric + circles), when `circle` is past the last one, when `ids` names an object twice, when the shapes lie at one point or + are too small for the radius, above 2,000 segments in all, and when the search for other shapes goes past its + limits. → `{ids, found}` (`found`: how many circles touch the shapes). Tangent Circle… opens a dialog + (`ui.menuDialog {command}`, kind `tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a + Circle menu (All, or one circle by number, as many as the last preview found) and Preview, which starts on. - `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?, minAngle?, maxAngle?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and `anchors` the anchor indices of each path's outline with no corners cut; without `anchors`, a path's direct-selected diff --git a/docs/revolve.md b/docs/revolve.md index 7e80ee3e24..922a1218e2 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -75,10 +75,19 @@ orthographic view); a partial turn produces a sector. Body faces share the same so no triangle patches interrupt the cap edge. Caps share the surface's rotation, perspective and paint, and appear in preview, SVG/PDF export and Expand Appearance. The checkbox has a reset dot and is included in Reset all. -An endpoint on the axis needs no cap. Closed profiles and open profiles whose endpoints coincide -keep their existing geometry. Each open subpath of a compound profile is capped independently. -A partial revolve adds only the swept sector at each endpoint; the angular cut sides remain open. -This option does not make intersecting or compound profiles into a watertight solid. +An endpoint on the axis needs no cap. Each open subpath of a compound profile is capped independently. + +With an Angle below 360°, Cap also closes the two angular cut sides, so the object appears solid; with Cap +off it is hollow ([Revolve options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). +Each cut side is flat and uniformly shaded, and is drawn in depth order with the rest of the surface. It covers the +region between each open subpath and the axis, and the area the closed subpaths fill together under the object's +fill rule, with one face for each region. A closed subpath that walls a hole leaves that hole open in the face of +the region around it, and where closed subpaths overlap, the overlap is filled or left open as the fill rule fills +it. A self-intersecting open subpath, or a self-intersecting closed subpath that is the only closed one, fills what +the nonzero rule fills, with one face for each loop it encloses; this is VectorCraft's own rule. A cut side seen edge +on is not drawn. +The cut sides appear in preview, SVG/PDF export, Expand Appearance, Expand as Wireframes, Revolve (Classic) and +exported 3D meshes. Cap does not make intersecting profiles into a watertight solid. In **Advanced**, **Keep visible surfaces only when expanding** is on by default. Expansion removes completely covered faces and trims partially covered ones using the current rotation and perspective. @@ -98,12 +107,12 @@ with the standard command. - Lighting offers Standard, Diffuse, Top Left and Right, using the [shared original rigs](three-d.md#presets). Other effective settings show Custom; changing the view does not change the recognized lighting preset. - Paths, compound paths, type, clipping groups, blends, symbol instances, and groups or layers of them. A clipping group, a blend or a symbol instance sweeps the art it shows about one axis, as described in [three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances). Images must be traced first with Object › Image Trace › Make, and other live objects expanded. -- Open profiles have circular end caps by default; turning Cap off keeps them open. Partial-sweep angular cut sides remain open. Closed profile boundaries are swept as provided. +- Open profiles have circular end caps by default, and a partial sweep closes its angular cut sides; turning Cap off keeps both open. Closed profile boundaries are swept as provided. - One Revolve per source object. Edit its options rather than applying another. - Object-level Revolve uses the top visible fill, falling back to a stroke. Per-item Revolve uses that item's paint. - Smooth diffuse shading, one to ten directional lights, no textures, cast shadows or physical materials. Smooth shading interpolates lighting in projected triangles; it does not smooth the silhouette or add specular highlights. - Faces are drawn back to front by the depths of their centers. When that order draws the nearer of two overlapping faces of a surface first, every pair of overlapping faces goes in the order of their depths at the middle of where they overlap; the sort compares at most 4,000,000 pairs (VectorCraft's own limit), and the pairs past that keep the depths of their centers. Caps facing the camera cover their rim seams; a cap facing away is drawn behind the body except where it is nearer than a body face it overlaps. Intersecting profiles can have incorrect visibility. -- Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. +- Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit, and each region of a cut side counts as one face. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit. - Axis, bounds and ordinary selection handles continue to refer to the editable 2D source profile. - Extrude & Bevel, Inflate and Rotate are described in [three-d.md](three-d.md). Materials remain unimplemented. diff --git a/docs/roadmap.md b/docs/roadmap.md index da1645efb2..fae091f647 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -159,7 +159,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | @@ -208,6 +208,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimates unchanged | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fdb66b722f..053fe68acd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -249,7 +249,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | @@ -381,7 +381,7 @@ Depth here is "does the basic use work", not the area's full score. | Shape tools (rectangle, ellipse, polygon, star, line) | 9 | 95% | all shape tools, Live Corners | | Selection, move, scale, rotate | 9 | 92% | bounding box, smart guides, transform tools | | Pen and Pencil, basic use | 7 | 88% | [ui-parity.md](ui-parity.md); a few Pencil and Curvature options missing | -| Fill, stroke, colour, swatches | 9 | 95% | M3 done; transform-aware Eyedropper character dimensions (#6404); highlighted-text Eyedropper font/paint and source/target transparency refusal regression-tested; scores and hours unchanged | +| Fill, stroke, colour, swatches | 9 | 95% | M3 done; Color spectrum fills a resized panel (#8005); transform-aware Eyedropper character dimensions (#6404); highlighted-text Eyedropper font/paint and source/target transparency refusal regression-tested; scores and hours unchanged | | Gradients, basic | 4 | 90% | Gradient panel and on-canvas annotator | | Type: point and area text, font, size | 8 | 88% | font menu with previews; Hyphenation… and Justification… options per paragraph (#2310, #2755) | | Align, group, arrange | 6 | 95% | | @@ -612,6 +612,7 @@ since 2026-10-01. **Drawing tools — Polygon and Star counts:** The existing canvas placement dialog reads the stored count and saves it only after successful placement. `polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs` covers both tools, repeated drags, tool switching, reopening and Cancel. Counts remain session tool options. Existing click and toolbar gestures are retained; no score or hour change. **Drawing tools, Star inner radius held with Ctrl/Cmd:** While a star is dragged out, Ctrl/Cmd keeps the inner radius the star showed when the key went down, also when the key is pressed with the pointer still. `a_star_drag_holds_its_inner_radius_with_ctrl_and_straightens_with_alt` and `a_star_drag_holds_the_inner_radius_it_shows_when_ctrl_goes_down` cover it, with Alt's straight shoulders and a drag canceled with Escape. +**Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. @@ -641,7 +642,8 @@ since 2026-10-01. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged. -- **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of type, images, symbol instances and groups, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged. +- **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of groups, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged. +- **Raster effects before a Transform effect that copies type, an image or a symbol instance:** each copy that a Transform effect makes of type, an image or a symbol instance now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before that effect, under the same VectorCraft rule as for paths: its sizes scale by that copy's mean scale and a Drop Shadow's offset turns, reflects and scales with the copy, while a raster effect listed after the Transform effect paints once around all the copies. Type is copied as its outlines, an image in its frame, and a symbol instance as its symbol's art. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies; type whose Transform effect only moves its copies is exported as its outlines then, rather than as type under one shadow (effects `tests::rasterfollow::each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it`, `tests::rasterfollow::baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each`, `tests::rasterfollow::type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies`; render `objectfx::each_copy_of_an_images_transform_effect_draws_its_own_shadow`, `objectfx::each_copy_of_a_symbol_instances_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_on_type_expands_as_the_canvas_draws_it`). Not yet: type and symbol instances in perspective, type, images and symbol instances whose fill or stroke has geometry effects of its own, and objects with a linked opacity mask keep one set of raster effects around their copies. Scores and hours unchanged. - **Rasterize before a Transform effect:** effects apply in the order they are listed, each one taking the result of the one before ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). On a path or compound path, a Transform effect listed after the object's own Rasterize effect now moves the image that Rasterize makes: the image is made of the art before the Transform effect, at the Rasterize effect's resolution and with its room around the art, and the Transform effect scales, turns, reflects and moves the image with its pixel grid. Before, the Transform effect moved the art and Rasterize made a new image of the moved art on a grid square to the page. Keeping the image's pixel grid under the Transform effect is VectorCraft's own rule. A hidden Transform effect, or one with Transform Objects off, leaves the image where it is, and one that scales it to nothing leaves nothing drawn. The canvas, the object's bounds, Expand Appearance and PDF export draw the same image (effects `tests::rasterfollow::rasterize_following_ignores_hidden_and_objects_off`, `tests::rasterfollow::the_image_moves_by_each_transform_about_the_art_it_takes`; render `rasterize::rasterize_then_scale_uses_the_pretransform_pixels`, `rasterize::rasterize_then_rotate_and_reflect_moves_the_pixel_grid`, `rasterize::rasterize_then_nonuniform_scale_and_zero_scale_are_bounded`; engine `rastersettings::expand_rasterize_then_transform_matches_canvas`). Not yet: a Transform effect that makes copies or moves at random, a Transform effect followed by another kind of effect, a fill's or stroke's own Rasterize effect, and Rasterize on type, images, symbol instances and groups keep the earlier behavior. Scores and hours unchanged. - **Raster effects before a Transform effect past the effect budget:** VectorCraft leaves out a Transform effect whose result would pass its geometry budget of 2 million anchors or 8 million lines drawn, and the art stays where it was. The raster effects listed before that Transform effect now stay with the art too: a Drop Shadow keeps its own offset and blur, and the Transform effects after it that fit still move both. Before, the art stayed while the shadow scaled with the Transform effect it did not take. This is VectorCraft's own rule. It applies to a path's own effects and to its fills' and strokes' own, also when the path is in a group whose geometry effects run after its members' own, on the canvas and in its bounds, in export, Expand Appearance, Object › Expand and Outline Stroke, and a hidden shadow keeps its values once shown (effects `tests::rasterfollow::a_transform_past_the_line_budget_moves_the_art_with_its_shadow`, `tests::rasterfollow::only_transforms_that_ran_move_a_preceding_shadow`, `tests::rasterfollow::a_skipped_item_transform_keeps_its_shadow`, `tests::rasterfollow::the_shape_art_of_a_skipped_transform_keeps_its_shadows`, `tests::rasterfollow::a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects`; render `objectfx::a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn`, `fx::renderer::tests::a_path_paints_from_the_transforms_that_moved_it`; engine `objexpand::a_shadow_before_a_skipped_transform_expands_with_its_own_offset`). Not yet: the shadow of type, an image, a symbol instance or a group whose art a Transform effect leaves in place past the budget still follows that effect. Scores and hours unchanged. - **Raster effects inside an object or group with a Transform effect:** effects applied to a group affect everything in it ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). How a Transform effect changes the raster effects inside a group or object is VectorCraft's own rule. A group's Transform effect that moves it once now transforms the raster effects of its members, of their fills and strokes, of nested groups and of the art of the linked opacity masks in it, after the members' own Transform effects. A raster effect that a member's own Transform effect with copies or random holds back keeps its value through that effect and still transforms with the group's. VectorCraft applies the same rule to the raster effects of an object's fills and strokes under the object's Transform effect. Sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, with Scale Strokes & Effects on or off. Before, they kept their values, or with Scale Strokes & Effects on scaled by the mean scale with the offset unturned. A group's or object's Transform effect that makes copies or moves at random leaves them as before. The canvas, the redraw region, export, Expand Appearance, Object › Expand and Outline Stroke use the same values (effects `tests::rasterfollow`, `group::tests::a_compound_shapes_transform_turns_its_fills_shadow`; render `a_transform_scales_the_shadows_of_fills_and_members_with_the_art`; engine `objexpand::a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it`, `objexpand::shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them`, `outlinestroke::a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it`). Scores and hours unchanged. @@ -670,6 +672,7 @@ since 2026-10-01. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. +- **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit leaves out groups holding type or images:** Select › Start Global Edit on a group that holds type or an image, at any depth, refuses to start, and such a group is not taken as a match, as Global Edit does not take images or text ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test for a group holding type: `global_edit_needs_one_supported_object` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. @@ -719,6 +722,7 @@ since 2026-10-01. - **Composite fonts that two documents define differently:** when two open documents each define a composite font (Type › Composite Fonts…) by the same name with different parts, each document draws and exports its type in its own definition: in a tiled or floating window drawn while the front document draws, when it is placed in a document that defines the name differently, and in an export made while another document is in front. Evidence: `tests::composite::nested_loans_of_one_name_use_each_documents_definition` and `threads_lending_one_name_at_once_use_their_own_definitions` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` (`crates/render`). Scores unchanged (estimated). - **Composite fonts only another document defines:** a document draws, measures and exports its type only in the composite fonts it defines itself. Type naming a composite font that only another open document, or the document a placed document sits in, defines is set as in a missing font, also when the document defines no composite font: in a window, a thumbnail or an export of a document in the back, in a file being opened and in a placed document. A temporary document drawn while a document draws keeps that document's composite fonts. Evidence: `tests::composite::a_lent_document_does_not_use_another_documents_composite_font` and `a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` and `a_document_draws_type_in_another_documents_composite_font_as_missing` (`crates/render`), `a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing` (`crates/engine`). Scores unchanged (estimated). - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). +- **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). - **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -890,6 +894,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG output under `--automation-read-root`: `document.serialize`, `document.export`, `document.exportSelection`, `document.exportForScreens`, `assets.export`, the SVG and SVGZ saves, `file.exportAs` and the SVG Options dialog's Show Code refuse an SVG or SVGZ of a document that links a JavaScript file outside the read roots, before any file or folder is written, with an error that names no file or folder; a URL, a file inside the roots and a relative path that leads inside them are written as stored, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/interactivity.rs` (`confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `svg_output_keeps_linked_javascript_files_a_caller_may_read`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots`). - Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. The check covers the art drawn for placed documents and leaves out what the file leaves out: hidden art in symbols, patterns and graph designs, opacity masks in SVG Tiny 1.2, and objects drawn as images for effects SVG has no filter for. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`, `confined_svg_output_checks_the_images_of_placed_documents`, `confined_svg_output_leaves_hidden_symbol_art_unchecked`, `confined_svg_tiny_output_leaves_opacity_mask_images_unchecked`, `confined_svg_output_checks_the_images_drawn_for_pixel_effects`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`). - Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`). + - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. @@ -974,6 +979,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). + - The status bar also translates the errors the script interpreter's core throws (an unknown name, a property of `null` or `undefined`, a property that cannot be defined, assigned or deleted and the reason, a value that is not a function or a constructor, an invalid array length, an invalid assignment target), on their own and in the line for a failed run, in every language that translates every message. Names, property names (a value a message quotes in `'…'` is shown as written, like one in `"…"`, even when it matches a translated message), `null`, `undefined`, `in`, `instanceof` and the error's type (`TypeError`, `ReferenceError` and the others) are shown as they are, and a script that catches the error still reads its English message. An error about a property of `null` or `undefined` names a computed property whose name is not an object and is at most 256 units long, and otherwise says only that the script read or set a property, instead of naming an empty property (`script_interpreter_core_errors_are_translated`, `errors_about_null_and_undefined_name_the_property`, `message_scan_reads_script_interpreter_errors`). - The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Hungarian catalog (`crates/ui-egui/src/i18n/hu.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,444 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Hungarian messages: the composite font, justification order and connect end errors that open #7211, #7116 and #7330 translate, and two messages that no catalog has a row for. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Dutch catalog (`crates/ui-egui/src/i18n/nl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,447 `@msg` rows in all. The report lists 41 Dutch messages: the composite font errors, the justification spacing error and the `connect` end error, which open #7211, #7116 and #7330 translate, and three unknown-parameter and range errors (``unknown parameter `{within}{key}`; {why}``, ``unknown parameter `{within}settings.{format}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`), which open #7353 rewrites so that a catalog row can match them. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. @@ -1005,6 +1011,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). + - A Recent Commands button beside the Help › Search Commands field lists the last five commands and tools picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). - The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their progress rings and counts of tutorials finished; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list`, `learn.tab {tab}`, `learn.skill {skill}`, `learn.show {tutorial}` and `learn.back` script it, and the tab buttons, the rows and Back run them ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). - A tool's name in a Learn tutorial step is a blue link that shows where the tool is without choosing it (`learn.locateTool {tool}`): its toolbar button is marked, a collapsed group's flyout opens with the tool's row marked, a torn-off strip comes to the front, and a tool no shown toolbar holds is marked in the All Tools drawer. The mark, its 3 seconds and the hidden-toolbar cases are VectorCraft's own rules ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`, the `a_learn_link_*` tests in `toolbar::tests`). - Under a tutorial's steps, View more opens the tutorial's own practice sample as a new untitled document, and once the tutorial is finished, Next Up moves to the next tutorial in the same skill, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). The samples are VectorCraft's own drawings. A Finish tutorial button that shows once the sample is open, the untitled copy, Back to skills in place of Next Up after a skill's last tutorial, and Next Up showing the next tutorial without opening its sample are VectorCraft's own rules. `learn.openSample`, `learn.finish`, `learn.next` and `learn.skills` (Back to skills) script them. Not done: the help page's short video. Regression tests: `view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document`, `finishing_a_tutorial_offers_next_up_in_its_skill`, `the_practice_controls_work_from_the_keyboard`, `the_last_tutorial_of_a_skill_offers_back_to_skills`, `learn_finish_and_learn_next_follow_the_practice`, `learn_skills_shows_the_list_of_skills`, `the_practice_commands_reject_a_missing_or_unknown_tutorial`, `every_tutorial_has_its_own_readable_sample` and `the_next_tutorial_is_the_next_one_in_the_same_skill` in `crates/ui-egui/src/panels/learn/tests.rs`. @@ -1172,6 +1179,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. + `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). With the Blob Brush, Shift held during a drag keeps the stroke on the horizontal or vertical line through the press point, whichever is nearer to the pointer (90° steps from the Constrain Angle preference), and the points dragged since Shift went down move to the other line when the pointer crosses to it; the points dragged while Shift is up follow the pointer. With the Blob Brush, Alt held before the press, or pressed before the drag has moved, switches to the Smooth tool, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists: the cursor shows the Smooth tool (Not Allowed with no path selected that it can act on), the drag shows a thin line and, with a path selected that it can smooth, the dashed band it smooths, without the length label, Shift does not constrain it, and the release smooths the selected paths under the drag (`path.smoothRegion`) instead of painting; with nothing selected the release changes no path. A stroke that has moved keeps painting when Alt goes down. Curvature point markers are circular, with no direction handles. While drawing, its own point feedback replaces generic selection markers; existing paths use the selection overlay, including partial selections and Hide Edges. Anchor Size applies, and Direct Selection and Pen retain their handles. The real egui-frame regressions in `crates/ui-egui/src/canvas.rs` verify marker positions, counts and unchanged documents (#1236, in part); the existing-path interpolation request remains open. The curve through the points (`curvature_spline` in `crates/tools/src/draw2.rs`) makes each stretch of three points follow the circle through them: a smooth point's handles lie along that circle's tangent, each `chord / (3 cos²(α/2))` long (α between handle and chord, capped at 90°), and the ends of an open path mirror their neighbour's tangent in their chord, so a J or a U curves evenly, a turn tighter than 30° comes to a point, and uneven spacing doesn't loop; the rubber band, a dragged or inserted point and `path.convertAnchor` to smooth use the same rule, while the Pencil's fitting keeps its own; `tests/draw2.rs` checks that the rubber band is the path the click makes (#1236, in part). The Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512). A path the Smooth tool changes stays selected whole, and the anchor points and segments selected on it with Direct Selection are deselected. Selected paths the drag does not change keep their selected anchors, and undo restores the earlier selection (`tests/draw2.rs`, `smoothing_a_path_drops_its_direct_selected_anchors`). While the Smooth tool drags with a path selected that it can smooth, a dashed outline shows the band it smooths: everything within its radius of the drag (12 screen pixels, VectorCraft's own value), round at both ends; Alt smoothing with the Pencil, Paintbrush and Blob Brush shows the same band. @@ -1196,7 +1204,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). - The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The outline of a drag with a round Eraser tip is drawn whole each frame. + The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). @@ -1227,7 +1235,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. As VectorCraft's own rule, the axis lines and tick marks, and separately a radar graph's rings, keep the paint, weight, opacity and blend mode of their topmost fill and stroke rows and their object opacity and blend mode through the graph being drawn again after a paint, stroke weight, gradient, recolor, Appearance, Transparency or Graphic Styles edit, the Eyedropper, Swap Fill and Stroke or Default Fill and Stroke, the frontmost line of a kind setting what the kind keeps; the lines' dashes, caps, joins and arrowheads are not kept. An Appearance, Transparency (with a fill or stroke row) or Graphic Styles edit given the Axes group or the Legend group reaches the lines and labels in it and is kept the same way. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are. What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. @@ -1428,7 +1436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`. - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`. The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`). @@ -1542,7 +1550,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel. - **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`. - **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`. -- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` group under its paths, with 1.5 px strokes along the edges two filled paths share, in the lower path's color (VectorCraft's own width), so renderers that anti-alias each path on its own show no light hairline along those edges. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` in `crates/engine`. Scores and hours unchanged. +- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box within the traced paths' box; on an image stretched more one way than another, each stroke's outline in image pixels is a filled path instead. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` and `image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge` in `crates/engine`. - **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)). - **Image Trace, nearly flat dark grounds:** with a Limited palette of 9 to 16 colors (16 Colors, and Document Library without swatches), by VectorCraft's own rule, a cut whose two sides both have a dark gray mean (Oklab lightness under 0.30, chroma under 0.03) and lie less than 0.03 apart in Oklab has its gain scaled by (distance / 0.03)². A near-black ground with faint noise then traces in one color, and the color it would have taken goes to another cut. Code-drawn tests `a_nearly_flat_dark_ground_keeps_one_color`, `only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides` and `a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color` in `crates/trace`. - **Image Trace, Document Library keeps neutral tones neutral:** each pixel takes the library color nearest in Oklab with differences in hue and chroma counted three times, so a gray or a muted brown traces as a neutral library color instead of a saturated one of similar lightness; a code-drawn test of gray and brown patches with a black, light and blue library in `crates/trace`. @@ -1583,6 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). + While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own. @@ -1647,6 +1656,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Swatches panel's menu has its own Show Recent Colors item: unchecking it hides the panel's Recent Colors row and checking it shows the row again ([Color Enhancements in Illustrator](https://community.adobe.com/announcements-651/color-enhancements-in-illustrator-816797) puts recent colors in the Color and Swatches panels; [Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html) hides them with Show Recent Colors in the panel menu; a [community thread](https://community.adobe.com/questions-652/swatches-disappear-in-swatches-panel-when-switching-between-documents-in-29-7-1-on-macos-816823) turns it off from the Swatches panel). In VectorCraft it is checked by default, kept between sessions apart from the Color panel's, and applied colors still join the list while the row is hidden (#6617). Tests: `show_recent_colors_hides_and_shows_the_swatches_row` in `crates/ui-egui/src/panels/swatches/tests.rs`. A Recent Colors chip in the Color or Swatches panel drags into the Swatches panel's list to become a swatch of its color, in its color model, as one undo step ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). In VectorCraft a chip dropped on a color group or one of its swatches joins that group, anywhere else in the list it joins the ungrouped swatches at the end, a color that is already a swatch is added again under another name, and dragging a chip does not paint the selected art (`swatch.new`). Tests: `a_recent_color_dragged_onto_the_list_becomes_a_swatch` and `a_recent_color_dragged_from_the_color_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/swatches/tests.rs`. A Cmd/Ctrl-click on the Color panel's spectrum applies Complement and a Cmd/Ctrl+Shift-click applies Invert to the active Fill or Stroke (`paint.complement`, `paint.invert`); with Alt also held, the click recolors the inactive one, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) list them. + The Color panel spectrum grows into the vertical space of a resized panel, with Show Options or Hide Options (#8005); compact auto-fit flyouts and embedded mixers retain their previous height. Regression: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). @@ -1658,7 +1668,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. + - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. @@ -1724,6 +1734,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). When an export bakes a symbol instance with geometry effects inside the art of another such instance, it counts the art the inner instance bakes to, the copies its symbol's effects make included, against the 262,144 objects of symbol art one export bakes that way; it counted only the symbol's art before its effects. An instance whose baked art would pass that count stays an instance with its effects, and the art baked for it still counts against the instances after it. These are VectorCraft's own limits (effects `bake::nested_reshape_counts_baked_art`, `nested_reshape_refusal_keeps_its_work_counted`, `nested_reshape_refused_siblings_bake_once`, `nested_reshape_counts_successful_descendants_once`). A raster effect (Drop Shadow, Outer Glow, Gaussian Blur and the other effects that paint pixels) on a symbol instance's topmost fill draws on each filled shape of the symbol's art, and one on its topmost stroke draws on each stroked shape, after any geometry effects listed before it, under the same rules as geometry effects: only a visible fill or stroke with an opacity above 0 counts, a group's own fills and strokes in the art take the effect, and an instance inside the art passes it on. Each shape gets its own shadow or glow, which is VectorCraft's own rule. The canvas, Use Preview Bounds and the drawn bounds, SVG and PDF export draw it, and Object › Expand Appearance is enabled for such an instance and makes the effect an image at the document's raster effects resolution, in one undo step (engine `expand::a_symbol_instance_fill_shadow_shadows_its_filled_art`, `a_symbol_instance_stroke_shadow_shadows_only_its_stroked_art`, `a_symbol_instance_fill_shadow_follows_the_fill_offset_before_it`, `a_nested_symbol_instance_takes_the_outer_fill_shadow`, `export_draws_a_symbol_instance_fill_shadow`). Existing documents with a raster effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. + Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own limits); an object or instance whose image would go past them stays as it is, with its raster effects, and the result reports how many with `rasterLeft` and a warning. Within those limits no live instance or raster effect is left from those effects, so the result no longer changes with the symbols; an instance left by the image limits still follows its symbol. The help page describes Expand Appearance turning appearance attributes into objects, and the help page describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`, `nested_instance_raster_effects_stop_at_the_image_limit`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. @@ -1836,6 +1847,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes point type, area type and type on a path as type in its editing copy, and objects next to it keep their own transparency (`crates/eps/src/ai_editing/tests.rs`, `cmd::fileio::tests_pdfedit::type_comes_back_from_the_editing_copy`; [file-format-parity.md](file-format-parity.md) lists what is written as outlines). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`). + A clipping object whose clipped art is written cut to it (a group, an image, a symbol instance, type, or a path or compound path inside art cut to another clipping object) keeps its Text Wrap Options in the editing copy on an unpainted path, or compound path, of the outline area type wraps around, under the art it clips and locked or hidden as the object is. The `.ai` reader reads an unpainted path (`paint` in `crates/eps/src/import/ai/read/art.rs`) and gives it the options of the dictionary after it (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so area type below the object wraps the same way when the file is opened. Without room for that path under the object limit, the options are left out (`crates/eps/src/ai_editing/tests.rs` `a_clipping_object_not_written_whole_keeps_its_text_wrap`, `a_clipping_objects_text_wrap_is_left_out_without_room`). Area type wrapped only by plain saved paths, compound paths or groups remains editable in the `.ai` editing copy when each frame's wrap recomputes unchanged; other wrapped area type remains outlines. The `.ai` reader works the wrap out again from the objects above the type (`resolve_text_wrap` in `crates/eps/src/import/native/build.rs`), so the writer keeps type only where each wrap object is written as itself (one path with no paint, a solid fill or a plain solid stroke, a compound path of visible members, or a group of such objects, without effects, an opacity mask or clipping), its offset is within -1000 to 1000 pt, and the shapes of every area type in the file stay within the 2,000,000 anchors the reader copies; when art is left out at the object limit, such type is written as outlines. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `area_type_wrapped_by_plain_objects_stays_type`, `area_type_wrapped_by_other_objects_stays_outlines`, `threaded_area_type_wrapped_by_plain_objects_stays_type`, `area_type_wrapped_on_a_large_canvas_stays_type`, `area_type_wrapped_past_the_reader_limit_stays_outlines`, `area_type_wrapped_past_the_object_limit_is_written_as_outlines`). Type written as its outlines in the editing copy still wraps area type by its bounds, not by its glyphs, when the file is opened: the outlines' group ends with an unpainted rectangle at the type's bounds that carries its Text Wrap Options, in the form the `.ai` reader reads a path's options (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), and the group keeps the type's name (`crates/eps/src/ai_editing/tests.rs` `type_written_as_outlines_keeps_wrapping_by_its_bounds`). A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). @@ -2225,6 +2237,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. Colored Inflate's facets lie over an underlay of themselves under one clip, so their shared edges show neither the black channel backdrop nor the background ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` compares 1:1 with 3x averaged down, and `colored_light_seams_stay_closed_in_svg_pdf_and_expansion` checks SVG, PDF and Expand Appearance. Colored Revolve's faces lie over an underlay of themselves the same way, run by run in a group and with mapped graphics kept after their faces; `colored_revolve_faces_leave_no_alpha_holes_at_one_to_one` checks that no pixel inside the art lets the background through at 1:1 where 3x averaged down is opaque, live, read back from SVG and PDF, and expanded. +Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::turned_colored_inflate_facets_and_seams_cover_their_edges_once` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. + ## Eyedropper character dimensions (2026-11-11) `appearance.copyFrom` reads the source's effective character dimensions and converts them into each target's local text space, preserving target placement, rotation, shear and reflection (#6404). Point and area text, grouped text, highlighted ranges, reverse and remembered sampling, attribute opt-outs, Undo/Redo and native-file round trips are regression-tested. Picks with unrepresentable dimensions or text that would extend beyond the canvas leave the document, paint defaults and remembered sample intact. Paint-only copying remains available. Tests: `crates/engine/src/tests/eyedropper.rs` (`scaled_type_pick_*`). Scores and estimates unchanged. @@ -2491,13 +2505,17 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Tangent Circle (2026-11-15) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Tangent Circle… (`addon.pathtools.tangentCircle`) draws the circles that touch two selected paths or compound paths at a set radius, or that touch three of them; for three circles these are the solutions of the [problem of Apollonius](https://en.wikipedia.org/wiki/Problem_of_Apollonius), up to eight. The rest is VectorCraft's own: a circle touches a shape when it meets the outline without crossing it (the whole outline outside the circle or inside it), so it is tangent at a smooth point and passes through a corner or an open end; circles, ellipses at any angle and other closed or open paths all take part, a compound path's members as one outline. Circles are solved in closed form, each answer then moved onto the drawn Bézier outlines; other shapes are searched on a grid and refined with Newton's method on the curves, and with three shapes circles up to 64 times the diagonal of the box around the shapes' anchors and handles are found. The circles are listed by radius, then top to bottom, then left to right; the dialog previews every circle found, or one picked by number, and OK draws them with the current paint as one undo step. No circle, more than 64 (shapes touched along a whole curve) and more than 2000 segments are errors. Tests: `tangent_circle::tests` in `vectorcraft-pathops` (three circles: two known circles and eight distinct ones in a steady order; two circles and a radius; the search against the closed form; rotated and skewed ellipses against an independent solve of every combination; two circles close together; squares; a compound path moved far off and scaled; open paths and the errors), `cmd::addons::pathtools::tangent_circle::tests` in `vectorcraft-engine`, `tangent_circle_previews_picks_one_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns the dashed stroke of each selected path and compound path into separate open paths, one per dash, for cutters and plotters that need the centre lines rather than Outline Stroke's filled outlines. The dashes are laid out by the renderer's own dash code, so they match what the canvas draws: the dash pattern, its offset and Align Dashes to Corners and Path Ends, a dash running on through the start of a closed path, a dash all the way round staying closed, and under a round or projecting cap each dot (a dash of no length) as a path on its point. Each dash keeps the path's appearance with the top stroke's dashes and arrowheads off; the path's fills stay on it, below its dashes; a compound path's dashes are plain paths. One undo step; the dashes are selected; at most 100000 (more, or a pattern too fine to draw, is refused). Tests: `expand_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (the stroke kept with dashes off, the offset, one undo step, the fill kept below, dashes centred on corners when aligned, dots under round and butt caps, compound paths, refusals and the piece cap), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (kept out of the shipped toolbars, listed in the All Tools drawer, no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Not yet: a highlight of the stretch under the pointer before the click, and crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (kept out of the shipped toolbars, listed in the All Tools drawer, no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Document Tools add-on: Save a Timestamped Copy (2026-11-01) @@ -2619,6 +2637,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index 5b93a7d7f6..0b8d879571 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -157,6 +157,11 @@ How a facet carries its seam depends on the lights and the paint: and from places where the light changes sharply, a pixel drawn at 1:1 is opaque where the 3x art is opaque, and otherwise its alpha is within 3 levels. Inflate seen straight on with an opaque fill also has each color channel within 3 levels (VectorCraft's own measure). + In the composite, a facet that is one closed polygon whose edges do not cross is drawn over the underlay as one + filled path, the facet and the outline of its round seam together, so a pixel at its edge is covered once and not + by a fill and then by a stroke of the same color. Other facets keep a fill and a seam stroke. Turned to X 50°, + Y 35° in an opaque fill, at most one color channel sample is more than 3 levels off the 3x art, and by at most 4 + (VectorCraft's own measure). - Extrude & Bevel (Classic), Rotate (Classic) and Revolve (Classic): a path and a seam for every face; gradient and pattern faces seam only the base paint, and the shading and highlight layers cover the face alone. The Wireframe surface draws edges only, with no seam. @@ -609,7 +614,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. across the shape) is refused because the 3D surface is too complex; a closed path of 65,536 points round a circle builds. - **3D (Classic)**: Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) are built, with their surface - types and blend steps. Revolve (Classic) sweeps the surface Revolve sweeps, at 64 segments for a full turn, and draws + types and blend steps. Revolve (Classic) sweeps the surface Revolve sweeps, with Cap closing a partial sweep's cut + sides ([revolve.md](revolve.md)), at 64 segments for a full turn, and draws every face back to front, so it has no Draw Hidden Faces setting. Rotate (Classic) turns the plane Rotate turns, seen from either side, with the No Shading and Diffuse surfaces only. Preserve Spot Colors, on the Lighting tab of all three, keeps a color linked to a spot or global swatch linked on every face: the highlight lowers its tint, and a diff --git a/docs/type-parity.md b/docs/type-parity.md index df082212b4..7697025ca9 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -32,10 +32,10 @@ against Illustrator's public documentation; **estimated** unless noted. | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. The glyph-cell pop-up of alternates is not there yet | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. A grid cell whose glyph has alternates shows a triangle in its lower right corner; a click on it opens a pop-up of that glyph and its alternates in the font's order, and a pick inserts the character at the caret drawn with that glyph, or draws the selected character with it, in one undo step; in Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)); the triangle's size and the pop-up's eight columns and six rows are VectorCraft's own (`panels::glyphs` tests `a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one`, `a_pick_replaces_the_selected_character_and_says_why_when_it_cannot`, `a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was`, `an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection`; `has_alternates_follows_the_listed_substitutions` in the text crate) | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | -| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice). | +| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`). | | Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG | | Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending | | Variable fonts | done | named instances as styles; Character panel › Variable Font sets each axis (`fontAxes`); the font menu's Font Technology › Variable lists only variable font families, with the script, kind and ★ filters ([Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html)); a family with a variable file beside static ones counts as variable. Evidence: `font_menu::tests::the_variable_filter_lists_only_variable_families`, `tests_axes::a_family_with_variation_axes_is_variable`, `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable` | @@ -75,7 +75,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: Standard Vertical Roman Alignment | done | Character panel menu › Standard Vertical Roman Alignment (`text.setFormat` / `text.setRangeStyle {standardVerticalRoman}`), with Show East Asian Options, off by default: in vertical type the marked half-width characters (Latin letters, digits and other characters that would lie on their side) stand upright one below the other, each in its upright cell; spaces keep their width and tate-chu-yoko blocks stay across the column; horizontal type keeps the mark and does not change. Character Style Options has its own checkbox for it. Evidence: `tests_vertical::standard_vertical_roman_alignment_stands_half_width_characters_upright`, `typecmd::standard_vertical_roman_is_a_character_attribute_saved_only_when_on` | | CJK: East Asian glyph forms | done | Glyphs panel menu › Traditional Forms, Expert Forms, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms, with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): the selected characters are drawn with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`; [feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)), one form at a time (`text.setFormat` / `text.setRangeStyle {glyphForm}`); a form none of the faces that draw the selected text (fallback faces included) has a feature for (in `GSUB`, or for the width forms `GSUB` or `GPOS`) is disabled, and Revert To Default Forms draws the default glyphs. A form other than the default takes away a character's glyph choice, and with a width form Proportional Metrics' `palt` is not applied and the font's pair kerning is off. Saved natively only when set, carried by character styles, drawn on the canvas and in PDF, and written to SVG as `font-feature-settings`. Character Style Options has no field for it. Evidence: `tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `typecmd::area_tests::a_glyph_form_takes_away_the_characters_glyph_choice`, `features::tests::width_forms_turn_off_proportional_metrics`, `panels::glyphs::tests::east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form`, `panels::glyphs::tests::glyph_form_items_at_a_caret_follow_all_the_text`, `panels::glyphs::tests::a_glyph_choice_lets_the_current_form_be_chosen_again` | | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | -| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Not yet: the Units menu, Show Sample. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | +| CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Serbian: Cyrillic, Serbian: Latin and Croatian); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). Not yet: hyphenation by it in languages other than English and the eleven Indian languages above, `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 293a7cf179..f956b98078 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -345,6 +345,7 @@ tools, never checked side by side) isn't captured row by row. | View › Hide Artboards (Ctrl/Cmd+Shift+H) hides the artboards' edges, bleeds, marks and names and shows the whole canvas as paper (white, or Simulate Colored Paper's colour); the Artboard tool still shows them | done | #4038, `canvas::tests::hidden_artboards_leave_a_paper_canvas_without_edges` | | Artboard Options › Display: Show Video Safe Areas and Video Ruler Pixel Aspect Ratio ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)) | done | #2849; per artboard (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1; one undo step; native format). The page gives no safe-area numbers: our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s, the action-safe area 3.5% and the title-safe area 5% in from each edge, outlined 1 point wide on the canvas and turned with the view; exports and print leave them out. Tests `an_artboard_shows_its_video_safe_areas`, `artboard_options_show_video_display_options`, `artboard_video_display_options_*` | | Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows | done | | +| Eraser: Shift-drag erases along a horizontal, vertical or diagonal line ([public source](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=82)) | done | the line runs from the press point at the 45° step from the Constrain Angle nearest the pointer, taken once the pointer is 3 screen pixels from the press and kept until Shift is released; the tip outline follows the line; released, the drag goes on freehand from the last point on the line, and Shift again takes a new step from the press point (VectorCraft's own rules); `eraser_shift_keeps_the_stroke_on_a_45_degree_line` in `crates/tools/src/draw2/gesture/tests.rs` | | Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | | Tool double-click opens its options | done | | | Per-platform mapping (Cmd ↔ Ctrl, Option ↔ Alt) | done | | @@ -484,8 +485,9 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its eight tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (in the All Tools drawer under the add-on's heading, in neither toolbar as shipped, no shortcut) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag every stretch its rectangle touches, an Alt-drag every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (in the All Tools drawer under the add-on's heading, in neither toolbar as shipped, no shortcut) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag every stretch its rectangle touches, an Alt-drag every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | @@ -552,6 +554,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. |