diff --git a/ROADMAP.md b/ROADMAP.md index b3877be5c8..236fc185eb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -154,6 +154,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 53e0484534..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -96,7 +96,24 @@ fn dialog_for(d: D, request: &PickRequest) -> D { Some(folder) => d.folder(folder), None => d, }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } + if pick.name.is_empty() { + return d; + } + // Windows' save dialog changes the extension when a different file type is chosen only when + // the suggested name has no explicit extension. rfd supplies the first filter's extension to + // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). + // A remaining dot in the stem would look like another explicit extension to Windows. + #[cfg(windows)] + if matches!(request, PickRequest::Save(_)) + && pick.filters.len() > 1 + && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) + && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) + && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) + && !stem.contains('.') + { + return d.file_name(stem); + } + d.file_name(&pick.name) } #[cfg(test)] @@ -796,7 +813,7 @@ mod dialog_tests { /// The file types a dialog was given, by label. #[derive(Default)] - struct Filters(Vec<(String, Vec)>); + struct Filters(Vec<(String, Vec)>, Option); impl DialogSettings for Filters { fn parent(self, _window: &winit::window::Window) -> Self { @@ -812,7 +829,8 @@ mod dialog_tests { fn folder(self, _folder: &str) -> Self { self } - fn file_name(self, _name: &str) -> Self { + fn file_name(mut self, name: &str) -> Self { + self.1 = Some(name.to_string()); self } } @@ -869,4 +887,24 @@ mod dialog_tests { let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); } + + /// A format selected after the Windows Save As dialog opens can replace the suffix of the + /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. + #[cfg(windows)] + #[test] + fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { + let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); + assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); + + let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); + let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); + let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); + } } diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index e803d867fc..9e78d17d4d 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -112,6 +112,18 @@ pub enum ArrowStyle { None, } +impl ArrowStyle { + /// The stroke arrowhead drawn at each end of the dimension line, or None for no head. + pub fn arrowhead(self) -> Option { + match self { + Self::Filled => Some(crate::Arrowhead::Triangle), + Self::Open => Some(crate::Arrowhead::TriangleOpen), + Self::Tick => Some(crate::Arrowhead::Slash), + Self::None => None, + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 0655c675dd..4365f7788a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -424,6 +424,44 @@ impl Document { out } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike + /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every + /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still + /// checks out, the nodes are found along those paths; otherwise one walk of the tree finds + /// them. As for every cached lookup, a second node given an existing id after the cache was + /// built is not found while the first one's cached path checks out (see [`id_index`]). + pub fn nodes_in_order(&self, ids: impl IntoIterator) -> Vec<&Node> { + let want: std::collections::HashSet> = ids.into_iter().collect(); + // As in `index_paths`, one walk is quicker than checking the cached paths of a good share + // of the document. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let mut paths = Vec::with_capacity(want.len()); + let cached = want.iter().all(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + paths.push(p); + true + } + _ => false, + }); + if cached { + // A node's path sorts after the paths of the nodes before it in tree order, its + // ancestors included. + paths.sort_unstable(); + return paths.iter().filter_map(|p| self.node_at(p)).collect(); + } + } + let mut out = Vec::new(); + if !want.is_empty() { + crate::id_index::note_tree_walk(); + self.walk(|n| { + if want.contains(&n.id) { + out.push(n); + } + }); + } + out + } + /// The node at index path `path` (as [`Document::index_path`] gives it). pub fn node_at(&self, path: &[usize]) -> Option<&Node> { let (first, rest) = path.split_first()?; diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6a32a21bbc..83b2a60446 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving /// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured /// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are -/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a +/// touched where the live geometry effects of a clipping path in their art show it, or where the +/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except +/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a /// 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 @@ -2104,20 +2106,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// 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) + marquee_with(doc, r, scope, leaves, false, false, false) } /// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer /// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as -/// the clicks of [`HitOptions::outline`] do. -pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false, outline) +/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides +/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the +/// top or inside a group, so a group is not taken for a guide in it (#8538). +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool, skip_guides: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline, skip_guides) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group /// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { - marquee_with(doc, r, scope, true, true, outline) +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool, skip_guides: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline, skip_guides) +} + +/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is +/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and +/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the +/// guides are hidden, [`HitOptions::skip_guides`] for the marquee). +#[derive(Clone, Copy)] +struct Rules { + whole_compounds: bool, + skip_guides: bool, +} + +impl Rules { + /// Is `n` a path made into a guide that the marquee leaves out? + fn skips(self, n: &Node) -> bool { + self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) + } } /// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? @@ -2125,8 +2146,17 @@ fn previews_off(n: &Node) -> bool { matches!(n.kind, NodeKind::Layer { preview: false, .. }) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { +fn marquee_with( + doc: &Document, + r: Rect, + scope: Option, + leaves: bool, + whole_compounds: bool, + outline: bool, + skip_guides: bool, +) -> Vec { let _walk = ArtWalk::open(); + let rules = Rules { whole_compounds, skip_guides }; let mut out = Vec::new(); // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. let locks = doc.locked_artboards_kept(); @@ -2140,7 +2170,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh 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)) }; + let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) }; c.iter() .enumerate() .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) @@ -2162,7 +2192,7 @@ 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, &symbols, r, outline, whole_compounds, None)) + .flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of @@ -2171,17 +2201,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// 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> { + fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, 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 drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline)); let inner = marquee_in_parent(l, r, outline); for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { @@ -2190,7 +2213,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh && !c.locked && !c.is_template() { - out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone())); + out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone())); } } else if !c.is_ruler_guide() { if drawn.is_some() { @@ -2207,12 +2230,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// 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>> { + fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, 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); + collect_leaves(a, s, r, None, rules, false, &mut ids); } Some(Rc::new(ids.into_iter().collect())) } @@ -2265,14 +2288,20 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// 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 { + /// compound paths, layers and groups are touched by their box, and an image or a symbol + /// instance also where its fills and strokes paint outside it ([`painted_touches`]). 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, rules: Rules, outline: bool) -> bool { + // Locked or hidden guides are not touched ([`Rules::skips`]). + if rules.skips(n) { + return false; + } // 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)); + return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false)); } match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), @@ -2283,25 +2312,41 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh c.visible && !shaper_hides(n, i, scope) && if i == 0 && n.clips() { - plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))) + plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline))) || clip_edge_touches(c, r, outline) } else { - inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + inner.is_some_and(|r| touches(c, s, r, scope, rules, outline)) } }) } - NodeKind::Compound { children, .. } if whole_compounds => { - children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) + NodeKind::Compound { children, .. } if rules.whole_compounds => { + // Guide contours left out ([`Rules::skips`]) don't make the compound a candidate. + children.iter().filter(|c| !rules.skips(c)).filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)), // A symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. In the art of another instance - // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). - NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art, or where the geometry effects of + // its active fill or stroke reshape the art ([`painted_touches`]). In the art of another + // instance walked outside that instance's box, it is touched only by its own art + // ([`ArtOnly`]) and those shapes. + NodeKind::SymbolInstance { .. } => { + !ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r)) + } + // An image is touched by its box, and outside it where its own fills and strokes paint. + NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r), _ => box_touches(n, s, r), } } + /// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol + /// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is + /// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when + /// `r` meets the reach of `n` ([`Node::reach_bounds_with`]). + fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { + let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; + n.reach_bounds_with(s).is_some_and(meets) + && image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r)) + } /// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of /// a symbol that draws a straight line) is touched where the marquee crosses it. fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { @@ -2315,7 +2360,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the /// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's /// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows. - fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool { + fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false }; let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) { @@ -2332,15 +2377,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh #[cfg(test)] ARTS_WALKED.with(|c| c.set(c.get() + 1)); let _art_only = ArtOnly::set(); - art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false)) + art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false)) } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, rules: Rules, outline: bool, out: &mut Vec) { 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 let Some(drawn) = touched_in_art(n, s, r, rules, outline) { if drawn.contains(&n.id) && !n.is_layer() { out.push(n.id); } @@ -2355,18 +2400,18 @@ 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) { - plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out)); + plain(true, || collect_leaves(c, s, r, scope, rules, outline, out)); } if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { out.push(c.id); } } else if let Some(r) = inner { - collect_leaves(c, s, r, scope, whole_compounds, outline, out); + collect_leaves(c, s, r, scope, rules, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds, outline) { + if touches(n, s, r, scope, rules, outline) { out.push(n.id); } } @@ -2401,14 +2446,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if leaves { let before = out.len(); if let Some(r) = r { - collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + collect_leaves(t, &symbols, r, scope, rules, outline, &mut out); } if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { out.push(t.id); } - } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) - || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) - { + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) { out.push(t.id); } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 9d0133ec60..a38f36f166 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang // So with a marquee across the art's left edge: in the view, only in Outline view. The // clipping path's own left edge lies there too, and counts in both. let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); - assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); - assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]); // `marquee_in` measures by the plain shapes, as its callers clip by them. assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); // Hidden, the effect no longer moves the region. @@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() { 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"); + assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art"); + assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place"); } } @@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() { assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None); } +/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at +/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group, +/// with leaves or without. The group's other members still take it, and with the guides unlocked +/// the guide does. +#[test] +fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let guide = |d: &mut Document, r: Rect| { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n + }; + let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0)); + let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0)); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art()); + let (top_id, inner_id, art_id) = (top.id, inner.id, art.id); + let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id()); + let nested = Node::group(nested_id, vec![Arc::new(inner)]); + d.insert(Some(l), 0, top).unwrap(); + d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap(); + let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0)); + for leaves in [false, true] { + let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip); + assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}"); + assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}"); + assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}"); + assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}"); + // Unlocked: the guides are touched. + assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}"); + assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}"); + } + // An enclosing loop's candidates leave them out alike. + assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty()); + assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]); +} + +/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all +/// locked or hidden guides, as the marquee does. +#[test] +fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let part = |d: &mut Document, r: Rect| { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0))); + let id = d.alloc_id(); + let mut compound = Node::group(id, vec![]); + compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() }; + d.insert(Some(l), 0, compound).unwrap(); + let r = Rect::new(0.0, 0.0, 60.0, 60.0); + assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden"); + assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked"); +} + /// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only /// while those shapes can be clicked (Construction mode, with them isolated), however deep it /// lies in them. @@ -2674,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}"); assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}"); assert!(marquee(&d, past, None, false).is_empty()); - assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view"); + assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view"); } // Preview off for the layer the instance is on. let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false); diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 42978c81b0..6f72655c1d 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -90,6 +90,42 @@ impl Node { matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. }) } + /// This object without the paths made into guides among the members of its groups, layers, + /// Intertwine groups and compound paths, at any depth, for measuring the art around them while + /// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or + /// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps + /// its structure. `None` when it holds no such guide. + pub fn without_guides(&self) -> Option { + let (NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Intertwine { children } + | NodeKind::Compound { children, .. }) = &self.kind + else { + return None; + }; + let keep = usize::from(self.clips() || self.extras().shaper.is_some()); + let mut changed = false; + let mut out = Vec::with_capacity(children.len()); + for (i, c) in children.iter().enumerate() { + if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + changed = true; + } else if let Some(stripped) = c.without_guides() { + changed = true; + out.push(Arc::new(stripped)); + } else { + out.push(c.clone()); + } + } + if !changed { + return None; + } + let mut n = self.clone(); + if let Some(c) = n.children_mut() { + *c = out; + } + Some(n) + } + /// A template layer (Layer Options → Template). pub fn is_template(&self) -> bool { matches!(self.kind, NodeKind::Layer { template: true, .. }) diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 4dd8394ce2..e91542fe1a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option { LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) } +/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the +/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written +/// as in an exported file. `None` for a language not in the list. +pub fn language_tag(language: &str) -> Option<&'static str> { + LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t) +} + /// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's /// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the /// first entry); `Err` for a language not in the list. @@ -404,6 +411,16 @@ impl DocSetup { mod tests { use super::*; + /// A document's language is written by its tag, the default's included (#3644). + #[test] + fn document_languages_have_their_tags() { + assert_eq!(language_tag(&DocSetup::default().language), Some("en-US")); + assert_eq!(language_tag("French"), Some("fr")); + assert_eq!(language_tag("german: swiss"), Some("de-CH")); + assert_eq!(language_tag("sr-latn"), Some("sr-Latn")); + assert_eq!((language_tag("Klingon"), language_tag("")), (None, None)); + } + /// Characters store a language of the list by its tag, the default as none. #[test] fn char_languages_are_stored_by_tag() { diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 863c7979cd..9c5c278a53 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() { } } +/// Every node whose id is in `ids`, by walking the tree. +fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> { + let mut out = vec![]; + d.walk(|n| { + if ids.contains(&n.id) { + out.push(n as *const Node); + } + }); + out +} + +/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids +/// included, with the cache built and without it, for a few ids (cached paths) and for many (a +/// walk). +#[test] +fn nodes_in_order_match_a_walk() { + for seed in 1..40 { + let (d, ids) = tree(seed); + let few: Vec = ids.iter().copied().step_by(17).collect(); + for cold in [true, false] { + if cold { + d.drop_lookup_cache(); + } else { + d.node(ids[0]); + } + for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] { + let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}"); + } + } + // An id that the tree repeats: every node with it. + let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue }; + assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once"); + // A second node given an id once held once, after the cache was built: the lookup finds the + // cached node, which has that id; with the cache built afresh, both. + let mut d = d; + let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer())); + let Some(once) = once else { continue }; + d.node(once); + let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, copy); + } + let found = d.nodes_in_order([once]); + assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}"); + d.drop_lookup_cache(); + d.node(once); + let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh"); + } +} + /// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each /// node it is in, appears in the tree once. fn picks(d: &Document, seed: u64) -> Vec { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b6a90c7164..a0fd8265dd 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -74,6 +74,7 @@ pub mod perspgrid; pub mod place; pub mod plugin; pub(crate) mod plugin_call; +mod preflight; pub mod prefscmds; pub mod print; pub(crate) mod printadvanced; @@ -382,6 +383,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(package::specs()); v.extend(slices::specs()); v.extend(print::specs()); + v.extend(preflight::specs()); v.extend(recovery::specs()); v.extend(fileio::dxfimport::specs()); v.extend(webexport::specs()); @@ -840,6 +842,8 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 8102777687..e45e736109 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -1,7 +1,8 @@ //! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected //! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without //! crossing into either, added as separate open paths, with the line joining their centers if -//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. +//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it +//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. #[cfg(test)] mod tests; @@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", has_selection, common_tangents )] } -/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, -/// else the path's one closed convex subpath. +/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact +/// ellipse for a whole live ellipse, else the path's one closed convex subpath. fn outline_of(d: &Document, id: NodeId) -> Result { const C: &str = COMMON_TANGENTS; let n = d.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if sp.anchors.len() == 1 + && let Some(only) = sp.anchors.first() + { + return pt::Outline::point(only.p).map_err(refusal); + } if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { let span = (pie.1 - pie.0).rem_euclid(360.0); if span < 1e-9 || 360.0 - span < 1e-9 { @@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let ordered = d.paint_order(roots.iter().copied()); let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + if a.is_point() && b.is_point() { + return Err(bad(C, "select two closed paths")); + } + // A point goes first, so that each line runs from it to where it touches the path. + let point = a.is_point() || b.is_point(); + let (a, b) = if b.is_point() { (b, a) } else { (a, b) }; let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); - let keep = |t: &&pt::Tangent| match kinds { - "external" => t.kind == pt::TangentKind::External, - "internal" => t.kind == pt::TangentKind::Internal, - _ => true, + // A point's external and internal tangents are the same lines: every kind keeps them. + let keep = |t: &&pt::Tangent| { + point + || match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + } }; let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); - let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let (external_kept, internal_kept) = match (point, kinds) { + (true, "internal") => (0, kept.len()), + (true, _) => (kept.len(), 0), + _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), + }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() && point { + // Written as `EngineError::Other` so that the i18n message scan finds it. + let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } if lines.is_empty() { // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one // external tangent means one path lies inside the other and touches it there; paths that diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index aef694bbdd..7ab6b32838 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() { assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); } +fn point(s: &mut Session, x: f64, y: f64) -> NodeId { + id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap()) +} + +#[test] +fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() { + let mut s = session(); + // The point is drawn after the oval, so it is the upper object; the lines still start at it. + let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap()); + let dot = point(&mut s, 100.0, 200.0); + select(&mut s, &[oval, dot]); + let before = steps(&s); + let r = s.execute(C, &json!({"centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 3, "two tangents and the centerline"); + let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points + // are x = -a²/200 = -8, y = ±b √(1 - x²/a²). + let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt(); + for sy in [1.0, -1.0] { + let touch = c + Vec2::new(-8.0, sy * y); + assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}"); + } + assert_eq!(r["centerline"], r["ids"][2]); + assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]); + // Every `tangents` value gives the same two lines. + for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] { + let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}"); + assert_eq!(lines(&s, &r).len(), 2, "{kind}"); + } +} + +#[test] +fn a_point_below_the_path_still_starts_the_lines() { + let mut s = session(); + // The point is drawn first, so it is the lower object and needs no swap. + let dot = point(&mut s, 100.0, 200.0); + let round = circle(&mut s, 300.0, 200.0, 50.0); + let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 3, "two tangents and the centerline"); + let p = Point::new(100.0, 200.0); + assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}"); + // From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long. + let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt(); + assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}"); + assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]); +} + +#[test] +fn a_point_on_or_inside_a_path_and_two_points() { + let mut s = session(); + let round = circle(&mut s, 200.0, 200.0, 50.0); + // On the circle: one line, centered on the point and as long as the circle is wide. + let on = point(&mut s, 250.0, 200.0); + let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap(); + assert_eq!(r["external"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}"); + // Inside: nothing changes, and the warning says why. + let inside = point(&mut s, 210.0, 190.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Two points, or a point and an open path, are refused. + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths")); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open")); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added"); +} + #[test] fn bad_selections_and_params_are_refused() { let mut s = session(); diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 34becd7c02..2f4d0388db 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, + BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive }, BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, @@ -374,6 +375,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) } } +/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen +/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering. +fn pressure_sensitive() -> BrushLibrary { + let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin())); + let pulse = group(vec![ + black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))), + ]); + let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { + art, + width: light, + width_mode: Some(Variation::Pressure), + width_max: Some(heavy), + colorization: Colorization::Tints, + ..Default::default() + }), + }; + let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush { + name: name.into(), + kind: BrushKind::Calligraphic(Calligraphic { + angle, + roundness, + size, + variation: [0.0, 0.0, variation], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]), + }), + }; + built( + "Pressure Sensitive", + Document::new(100.0, 100.0), + vec![ + art_pressure("Flex Ribbon", flex, 35.0, 250.0), + art_pressure("Pulse Stroke", pulse, 45.0, 280.0), + nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0), + nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0), + ], + ) +} + /// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for /// blending and texture. fn bristle_brushes() -> BrushLibrary { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 2af57fd063..c026a1086e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -211,7 +211,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 98e3ce714b..f5245bc9af 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); let pixel = pixel_grid_param(p, C)?.unwrap_or(false); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; + let iso = s.doc()?.isolation; // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); d.set_symbol_pixel_aligned(&name, pixel); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; Ok(json!({ "name": name, - "id": id.0, + "id": id.map(|i| i.0), "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 183cbd3746..955401b923 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc}; use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::dimension::{ - ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition, -}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition}; +use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = match o.arrow_style { - ArrowStyle::Filled => Some(Arrowhead::Triangle), - ArrowStyle::Open => Some(Arrowhead::TriangleOpen), - ArrowStyle::Tick => Some(Arrowhead::Slash), - ArrowStyle::None => None, - }; + let head = o.arrow_style.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 1ded8d1f0b..bd55624b32 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p } /// Does a file of a document with `artboards` artboards, written in format `format` with options -/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and -/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` +/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates, +/// EPS files and the files of an exporter plug-in's format (`plugin.`, whose plug-in is given +/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` /// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and /// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF /// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder @@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false)); match format { "svg" | "svgz" | "vectorcraft" | "template" | "eps" => true, + _ if vectorcraft_plugins::export::plugin_id(format).is_some() => true, "ai" | "ait" => { let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)); !legacy && !(format == "ai" && art_page()) && every_artboard() @@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu /// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: /// always, unless read roots are in force, the file carries the native document (a native file or -/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as +/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter +/// plug-in's file, as /// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file /// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the /// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 3e34dae7f2..8b5cd9fe6f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { /// The file exporter plug-in `plugin` writes of `doc` in its format `f` /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON -/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else -/// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). +/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots +/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path` +/// names (else one named after the document) with that path's extension when the plug-in lists it, +/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { use vectorcraft_plugins::{Error, export}; - let doc = &*doc.without_edit_modes(); + let doc = doc.without_edit_modes(); + let doc = &*super::access::with_readable_settings_folder(&doc); let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; let path = p.get("path").and_then(Value::as_str); let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 45689adc17..ef7420217b 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc], areas: super::typecmd::export_overflow_warning(&overflow) } +/// The objects behind production findings. Resource art points to its first visible owner on +/// the canvas, so a finding can be located without selecting an id outside the layer tree. +#[derive(Default)] +pub(super) struct PreflightType { + pub fonts: BTreeMap>, + pub overflow: BTreeSet, + pub images: BTreeMap, +} + +pub(super) fn preflight_type(d: &Document, layers: &[Arc], areas: &[Rect]) -> PreflightType { + let mut walk = Printed::new(d); + walk.preflight = Some(PreflightType::default()); + for l in layers { + walk.node(l, Some(areas)); + } + walk.preflight.unwrap_or_default() +} + /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, @@ -546,13 +564,25 @@ struct Printed<'a> { /// The symbols and patterns whose art was walked. symbols: BTreeSet, patterns: BTreeSet, + preflight: Option, + owner: Option, } impl<'a> Printed<'a> { /// A walk of `d` among its own objects, nothing found yet. fn new(d: &'a Document) -> Self { let boxes = d.symbol_boxes(); - Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() } + Self { + d, + boxes, + own: true, + fonts: BTreeSet::new(), + overflow: BTreeSet::new(), + symbols: BTreeSet::new(), + patterns: BTreeSet::new(), + preflight: None, + owner: None, + } } /// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit @@ -560,6 +590,15 @@ impl<'a> Printed<'a> { /// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live /// object) all of them but those outside the clipping path of a clip group. fn node(&mut self, n: &Node, areas: Option<&[Rect]>) { + let previous = self.owner; + if self.own { + self.owner = Some(n.id); + } + self.node_contents(n, areas); + self.owner = previous; + } + + fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) { if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) { return; } @@ -571,6 +610,14 @@ impl<'a> Printed<'a> { && !open && !self.meets(n, a) { + // An entirely overset frame paints nothing, but is still a delivery problem. Keep + // the export walk unchanged; only preflight checks the frame itself in this case. + if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind) + && n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b))) + && vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow + { + p.overflow.insert(owner); + } return; } // The art that its opacity mask, pattern paints and brushed strokes draw. @@ -616,16 +663,33 @@ impl<'a> Printed<'a> { if overflows && self.own { self.overflow.insert(n.id); } + if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + p.overflow.insert(owner); + } for r in runs { - self.fonts.extend(run_fonts(r)); + let fonts = run_fonts(r); + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + for font in &fonts { + p.fonts.entry(font.clone()).or_default().insert(owner); + } + } + self.fonts.extend(fonts); // Inline graphics draw their symbols' art. if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) { self.symbol(&art.symbol); } } } + NodeKind::Image(_) => { + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + p.images.entry(n.id).or_insert(owner); + } + } NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol), NodeKind::PlacedDocument(p) => { + if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) { + report.images.entry(n.id).or_insert(owner); + } for art in p.art(n) { self.art(&art); } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 437629cbae..4be83d7da6 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 4ae66430e7..7b1a97b4b3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -369,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -402,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -423,12 +421,47 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]); // A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal. let m = match p.get("axis") { diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 04c0d2ba51..e959f126c0 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Package", [], None, - "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied", has_doc, package )] @@ -113,27 +113,65 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of -/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. -fn carried_document(name: &str, bytes: &[u8]) -> Option { - if super::place::document::is_native(name, bytes) { - return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); - } - let data = - if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; - vectorcraft_format::load(&data?).ok() +/// The native document a linked file is or carries ([`carried_document`]). +enum Carried { + /// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file + /// without editing data. + Absent, + /// The native document, read. + Readable(Box), + /// The file is a native document, or carries one, that can't be read: a damaged native file, + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF + /// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file + /// whose attachments are too many to search to their end, or editing data that doesn't read as + /// a native document. + Unreadable, } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file. +fn carried_document(name: &str, bytes: &[u8]) -> Carried { + let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d))); + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc))); + } + if super::place::document::is_pdf(name, bytes) { + // A PDF that can't be opened may carry editing data all the same. + return match vectorcraft_pdf::open_pdf(bytes, None) { + // Attachments left unsearched may list another editing file, which can't be checked. + Ok(opened) if opened.editing_search_cut() => Carried::Unreadable, + // An editing file listed whose data can't be resolved can't be checked either. + Ok(opened) => match opened.editing() { + Some(e) => read(&e.data), + None if opened.has_editing_file() => Carried::Unreadable, + None => Carried::Absent, + }, + Err(_) => Carried::Unreadable, + }; + } + if !vectorcraft_eps::has_native(bytes) { + return Carried::Absent; + } + vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data)) +} + +/// The error for a linked file the package would copy whose native document can't be read to +/// check the files and folders it names against the read roots. +const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots"; + /// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the -/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a -/// relative path taken from the file's folder): the copy would name it. +/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file +/// outside them (a relative path taken from the file's folder): the copy would name it. A file +/// whose native document can't be read is refused, as its links can't be checked. The error names +/// no file or folder. fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { if crate::file_access::current().is_none() { return Ok(()); } match carried_document(name, bytes) { - Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), - None => Ok(()), + Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + Carried::Unreadable => Err(bad(C, UNREADABLE)), + Carried::Absent => Ok(()), } } @@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { return Ok(()); } match carried_document(name, bytes) { - Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)), + Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => { + Err(bad(C, FOLDER_OUTSIDE)) + } + Carried::Unreadable => Err(bad(C, UNREADABLE)), _ => Ok(()), } } @@ -498,6 +539,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?.doc.clone(); let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 20b3f18de2..fddd6cdd9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -274,8 +274,9 @@ impl DocState { /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?" /// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item) /// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of - /// each selected object's own stack is compared. One walk of the document, so callers that ask - /// every frame cache it by revision. + /// each selected object's own stack is compared. The selected objects are found through the id + /// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk + /// of the document, so callers that ask every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { self.proxy_mixed_with(item, &[]) } @@ -290,15 +291,17 @@ impl DocState { if self.selection.symbol_part.is_some() { return (false, false); } - let ids: std::collections::HashSet = self.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); - self.doc.walk(|n| { - if ids.contains(&n.id) { - selected.push(n); - painted(n, true, &mut nodes); - } - }); + // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); + let (mut selected, mut nodes) = (vec![], vec![]); + // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each + // place it appears. + for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { + #[cfg(test)] + tests::note_gathered(); + selected.push(n); + painted(n, true, &mut nodes); + } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; @@ -1323,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result { } s.execute("object.setProps", &Value::Object(q)) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs new file mode 100644 index 0000000000..3da5d73d9e --- /dev/null +++ b/crates/engine/src/cmd/paint/tests.rs @@ -0,0 +1,335 @@ +//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the +//! id cache: it answers as a walk of the whole document does, and with a few objects selected it +//! reads only those. + +use std::cell::Cell; +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{painted, picked_colors, proxy_paint, same_in_proxy}; +use crate::{DocState, Session}; + +thread_local! { + /// [`gathered`] of this thread. + static GATHERED: Cell = const { Cell::new(0) }; +} + +/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones. +pub(super) fn note_gathered() { + GATHERED.set(GATHERED.get() + 1); +} + +/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones. +fn gathered() -> u64 { + GATHERED.get() +} + +/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document. +fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { + if st.selection.is_empty() { + return (false, false); + } + if st.selection.symbol_part.is_some() { + return (false, false); + } + let ids: HashSet = st.selection.objects.iter().copied().collect(); + let (mut selected, mut nodes) = (vec![], vec![]); + st.doc.walk(|n| { + if ids.contains(&n.id) { + selected.push(n); + painted(n, true, &mut nodes); + } + }); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let differ = |stroke: bool| { + let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); + let set = if item.is_some() { &selected } else { &nodes }; + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); + let Some(p0) = paints.next() else { return false }; + paints.any(|p| !same_in_proxy(&p0, &p)) + }; + (differ(false), differ(true)) +} + +/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item +/// and with and without `points`, with the id cache built and without it. +fn agree(st: &DocState, points: &[(NodeId, Vec)], what: &str) { + for cold in [true, false] { + if cold { + st.doc.drop_lookup_cache(); + } + for item in [None, Some(0), Some(1), Some(2), Some(3)] { + for points in [points, &[]] { + assert_eq!( + st.proxy_mixed_with(item, points), + walked(st, item, points), + "{what}: item {item:?}, {} picked points, cold cache {cold}", + points.len() + ); + } + } + } +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap(); + id +} + +/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object, +/// different fills or strokes, a group with different contents, a group with one of its objects, +/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a +/// gradient mesh with points picked beside another object, ids not in the document and an id that +/// appears twice (a damaged file) with different paints. +#[test] +fn the_question_marks_match_a_walk_of_the_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let a = rect(&mut s, 10.0, "#ff0000", "#000000"); + let b = rect(&mut s, 40.0, "#0000ff", "#000000"); + let c = rect(&mut s, 70.0, "#ff0000", "#00ff00"); + // Two fills: [Fill, Stroke, Fill]. + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap(); + let e = rect(&mut s, 100.0, "#ff0000", "#000000"); + let f = rect(&mut s, 130.0, "#00ff00", "#000000"); + let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap()); + let mesh = rect(&mut s, 160.0, "#ff0000", "#000000"); + s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap(); + let hidden = rect(&mut s, 190.0, "#0000ff", "#000000"); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let h = rect(&mut s, 220.0, "#ff0000", "#000000"); + let missing = NodeId(999_999); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") }; + let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1)); + s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap(); + let points = vec![(mesh, vec![p00, p01])]; + let points_alike = vec![(mesh, vec![p01, p11])]; + + let selections = [ + vec![a], + vec![a, b], + vec![b, a], + vec![a, h], + vec![g], + vec![g, e], + vec![e, g], + vec![f, e], + vec![c], + vec![c, a], + vec![a, c], + vec![mesh], + vec![mesh, a], + vec![a, mesh, h], + vec![hidden], + vec![hidden, b], + vec![missing], + vec![missing, a], + vec![a, missing, b], + vec![a, a], + ]; + let check = |s: &mut Session, what: &str| { + for sel in &selections { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + agree(st, &points, &format!("{what}: {sel:?}")); + agree(st, &points_alike, &format!("{what}: {sel:?}, alike points")); + } + s.execute("select.all", &json!({})).unwrap(); + agree(s.active().unwrap(), &points, &format!("{what}: Select All")); + }; + check(&mut s, "unique ids"); + + // A second node with a's id and another fill, at the end of the tree. + let st = s.active_mut().unwrap(); + let mut copy = st.doc.node(a).unwrap().clone(); + copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let doc = Arc::make_mut(&mut st.doc); + let last = doc.layers.len() - 1; + Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy)); + doc.drop_lookup_cache(); + check(&mut s, "a repeated id"); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![a]; + assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill"); +} + +/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other +/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order. +fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + d.layers.clear(); + let mut rects = vec![]; + for l in 0..layers { + let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0)); + for _ in 0..groups { + let children = (0..per_group) + .map(|_| { + let id = d.alloc_id(); + let mut ap = Appearance::default_art(); + let red = rects.len() % 2 == 0; + ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) })); + rects.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap)) + }) + .collect(); + let group = Node::group(d.alloc_id(), children); + layer.children_mut().unwrap().push(Arc::new(group)); + } + d.layers.push(Arc::new(layer)); + } + (d, rects) +} + +fn state(doc: Document) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + s.active_mut().unwrap().doc = Arc::new(doc); + s +} + +/// With one object selected, the "?" reads only that object, not every node of the document, and +/// does not walk the tree once the id cache is built; with every object selected it walks the tree +/// once. +#[test] +fn the_question_marks_read_only_the_selected_objects() { + let (doc, rects) = big(2, 40, 25); + let mut s = state(doc); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![rects[777]]; + assert_eq!(st.proxy_mixed(None), (false, false)); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (false, false)); + assert_eq!(gathered() - read, 1, "only the selected object is read"); + assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers"); + + st.selection.objects = vec![rects[3], rects[1500]]; + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0)); + + st.selection.objects = rects.clone(); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!(gathered() - read, rects.len() as u64); + assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); +} + +/// Random selections of a document with nested groups answer as a walk does. +#[test] +fn random_selections_match_a_walk_of_the_document() { + let (doc, rects) = big(3, 12, 6); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let layers: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + let all: Vec = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect(); + let mut r = 0x2545_f491_4f6c_dd1d_u64; + let mut next = |n: usize| { + r ^= r << 13; + r ^= r >> 7; + r ^= r << 17; + (r % n as u64) as usize + }; + for round in 0..200 { + let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 }); + let sel: Vec = (0..count).map(|_| all[next(all.len())]).collect(); + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}")); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on +/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn proxy_mixed_timing() { + let (doc, rects) = big(5, 100, 100); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let cases: [(&str, Vec); 5] = [ + ("1 object", vec![rects[25_000]]), + ("2 objects, different fills", vec![rects[10], rects[40_001]]), + ("a group of 100", vec![groups[250]]), + ("all 500 groups", groups.clone()), + ("all 50,000 objects", rects.clone()), + ]; + const CALLS: usize = 200; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |"); + println!("|---|---|---|---|---|"); + for (name, sel) in &cases { + for cold in [false, true] { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}"); + let (mut old, mut new) = (vec![], vec![]); + let calls = if cold { CALLS / 10 } else { CALLS }; + for _ in 0..7 { + for (times, use_walk) in [(&mut old, true), (&mut new, false)] { + let d = time(|| { + for _ in 0..calls { + if cold { + st.doc.drop_lookup_cache(); + } + std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) }); + } + }); + times.push(d.as_secs_f64() * 1e6 / calls as f64); + } + } + let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::>().join(" "); + println!( + "| {name} | {} | {:.1} | {:.1} | {} / {} |", + if cold { "dropped before each call" } else { "built" }, + median(old.clone()), + median(new.clone()), + runs(&old), + runs(&new) + ); + } + } +} diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 096f90bf36..5106bb1148 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result { Ok(out) } +/// Resolution at a placed image's transform: 72 points per inch over each pixel axis. +pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] { + let [a, b, c, d, ..] = xf.as_coeffs(); + let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); + [ppi(a, b), ppi(c, d)] +} + pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { const C: &str = "image.info"; let st = s.doc()?; @@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { let doc = super::links::with_brush_art(&st.doc); let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; - // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. - let [a, b, c, d, ..] = im.xf.as_coeffs(); - let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); let size = n.geometric_bounds().unwrap_or_default(); // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. let doc_path = super::links::LinkBase::of(st).doc; @@ -1179,7 +1183,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, - "ppi": [ppi(a, b), ppi(c, d)], + "ppi": effective_ppi(im.xf), "width": size.width(), "height": size.height(), })) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 48a6649d77..5570dc6a81 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -161,6 +161,8 @@ pub struct FilterRun { parent: Option, /// The document it was made from, and that document's revision then. document: (u64, u64), + /// The plug-in's limits with the Plug-in Instruction Budget in force when it was made. + limits: vectorcraft_plugins::Limits, } /// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run @@ -245,7 +247,11 @@ impl FilterRun { let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len()); let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?; let document = (st.uid, st.revision); - Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document }) + let limits = match s.prefs.plugin_instruction_budget { + crate::PluginBudget::Normal => plugin.limits().clone(), + crate::PluginBudget::Large => plugin.large_limits(), + }; + Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits }) } /// The plug-in, for its name and budget. @@ -274,7 +280,13 @@ impl FilterRun { /// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between /// two slices of its budget. pub fn run(&self) -> Result> { - self.plugin.run(&self.input, &self.params).map_err(err) + self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err) + } + + /// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when + /// it was made. + pub fn limits(&self) -> &vectorcraft_plugins::Limits { + &self.limits } /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the @@ -289,7 +301,7 @@ impl FilterRun { let may = self.plugin.manifest().permissions(); let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args); - self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err) + self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err) } /// Runs a plug-in that calls commands and applies its output: the calls and the output are one diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs new file mode 100644 index 0000000000..ebfaf5deeb --- /dev/null +++ b/crates/engine/src/cmd/preflight.rs @@ -0,0 +1,133 @@ +//! Production preflight: the existing output-aware type walk, linked-file probes and image +//! resolution calculation, returned as findings that the interface can locate and recheck. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_text::{FontDb, FontMatch}; + +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param}; + +const COMMAND: &str = "document.preflight"; +const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"]; + +pub fn specs() -> Vec { + vec![cmd!( + query "document.preflight", + "Production Preflight", + [], + None, + "{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file", + has_doc, + check + )] +} + +fn check(s: &mut Session, p: &Value) -> Result { + let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf"); + if !matches!(output, "pdf" | "print" | "screen") { + return Err(bad(COMMAND, "output must be pdf, print or screen")); + } + let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?; + if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) { + return Err(bad(COMMAND, "minPpi must be from 1 to 9600")); + } + let indices = match p.get("artboards").filter(|v| !v.is_null()) { + Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?, + None => (0..s.doc()?.doc.artboards.len()).collect(), + }; + let context = if output == "print" { + super::print::preflight_context(s, &indices)? + } else { + let doc = &s.doc()?.doc; + let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect(); + super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] } + }; + let areas = context.pages.iter().map(|(r, _)| *r).collect::>(); + let st = s.doc()?; + let doc = st.doc.with_placed_art(); + let mut layers = doc.layers.clone(); + vectorcraft_pdf::keep_layers(&mut layers, context.layers); + let typed = super::fonts::preflight_type(&doc, &layers, &areas); + let statuses = super::links::statuses(st); + let mut findings = vec![]; + let db = FontDb::global(); + for (font, ids) in typed.fonts { + let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) { + None | Some(FontMatch::Missing) => "missingFont", + Some(FontMatch::Style) => "substitutedFont", + _ => continue, + }; + findings.push( + json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::>(), "name": super::fonts::font_label(&font) }), + ); + } + for id in typed.overflow { + findings.push(finding("text", "overflow", id, &doc)); + } + let mut resolution_unchecked = 0usize; + for (source, owner) in typed.images { + if let Some((status, _, _)) = statuses.get(&source) { + let code = match status.as_str() { + "missing" => Some("missingLink"), + "modified" => Some("modifiedLink"), + _ => None, + }; + if let Some(code) = code { + let mut f = finding("links", code, owner, &doc); + f["sourceId"] = json!(source.0); + findings.push(f); + } + } + // A vector placed document has no single bitmap resolution. Its embedded artwork, and + // resources with their own coordinate systems, must never be certified at a local scale. + if doc.node(source).is_none() || source != owner { + resolution_unchecked += 1; + continue; + } + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else { + resolution_unchecked += 1; + continue; + }; + let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n)); + let ppi = context + .pages + .iter() + .filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0)) + .map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf)) + .reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]); + let Some(ppi) = ppi else { + resolution_unchecked += 1; + continue; + }; + // Inverting the placed-size transform can round an exact threshold slightly down. + if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) { + resolution_unchecked += 1; + } else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) { + let mut f = finding("resolution", "lowResolution", owner, &doc); + f["effectivePpi"] = json!(ppi); + f["threshold"] = json!(min_ppi); + findings.push(f); + } + } + let checks = KINDS.map(|kind| { + let count = findings.iter().filter(|f| f["kind"] == kind).count(); + let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 }; + let status = if count > 0 { + "failed" + } else if not_checked > 0 { + "notChecked" + } else { + "passed" + }; + json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked }) + }); + Ok(json!({ + "output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks, + "findings": findings, "outputWarnings": context.warnings, + "limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."] + })) +} + +fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value { + json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) }) +} diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 14273ef002..774c450065 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -324,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), // Plug-ins & Scratch Disks p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text), + // The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input. + p!( + "pluginInstructionBudget", + "Plug-ins & Scratch Disks", + "Plug-ins", + "Plug-in Instruction Budget", + choice(&[("normal", "Normal"), ("large", "Large")]) + ), p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text), p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text), // User Interface diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 0826e848cf..8c507db007 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(v) } +/// Reuse the Print dialog's saved settings and page geometry for production preflight, without +/// printing, writing a file or duplicating its type warnings. +pub(super) struct PreflightContext { + pub layers: PrintLayers, + pub pages: Vec<(Rect, Affine)>, + pub warnings: Vec, +} + +pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result { + let settings = + json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::>().join(",") } }); + let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?; + super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?; + let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?; + let pages = pv + .sheets + .iter() + .filter_map(|p| { + let to_page = Affine::new(p.transform); + on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page)) + }) + .collect(); + pv.warnings.extend(pv.setting_notes); + Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings }) +} + /// The parts of the document (document space) that the pages of `pv` print. fn areas(pv: &PrintPreview) -> Vec { pv.sheets diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 76287e490d..1b5fec0a3b 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -76,7 +76,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; 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}", + "{name?, id?} | {name, from} 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. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. 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 ), @@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value { fn style_redefine(s: &mut Session, p: &Value) -> Result { let cmd = "graphicStyle.redefine"; - let (src, n) = source(s, p, cmd)?; - let d = &s.doc()?.doc; - // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. - let n = super::appearance::look_holder(d, n); - let src = if n.id == src { src } else { n.id }; - let i = match str_param(p, "name") { - Some(name) => style_index(d, name)?, - None => n - .extras() - .graphic_style - .and_then(|id| d.graphic_style_by_id(id)) - .and_then(|g| d.graphic_style_index(&g.name)) - .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + // The style to replace, its new look, and the object that look comes from (none for another style's look). + let (i, look, src) = match p.get("from") { + Some(from) => { + let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?; + if p.get("id").is_some() { + return Err(bad(cmd, "pass `id` or `from`, not both")); + } + let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?; + let d = &s.doc()?.doc; + let (i, j) = (style_index(d, name)?, style_index(d, from)?); + // A style dropped on itself, or on a style with the same look, stays as it is. + let target = &d.graphic_styles[i]; + let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() }; + if i == j || look == *target { + return Ok(json!({ "name": name })); + } + (i, look, None) + } + None => { + let (src, n) = source(s, p, cmd)?; + let d = &s.doc()?.doc; + // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. + let n = super::appearance::look_holder(d, n); + let src = if n.id == src { src } else { n.id }; + let i = match str_param(p, "name") { + Some(name) => style_index(d, name)?, + None => n + .extras() + .graphic_style + .and_then(|id| d.graphic_style_by_id(id)) + .and_then(|g| d.graphic_style_index(&g.name)) + .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + }; + (i, GraphicStyle::of(String::new(), captured(n), n), Some(src)) + } }; - let look = GraphicStyle::of(String::new(), captured(n), n); - let name = d.graphic_styles[i].name.clone(); + let name = s.doc()?.doc.graphic_styles[i].name.clone(); let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { @@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src); + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); let (follow, edited): (Vec, Vec) = linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); @@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. let mut follow_marks = super::graph::series_group_marks(d, &follow); let edited: HashSet = edited.into_iter().collect(); - follow_marks.retain(|nid| *nid != src && !edited.contains(nid)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid)); super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); let mut shared = None; @@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { } super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); super::graph::capture_label_rows(d, &follow_marks); - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } Ok(()) })?; Ok(json!({ "name": name })) diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 82ac2f9f76..7e0d790568 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() { } } +/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the +/// thread as it was: every frame stays a frame of the thread with the text it holds, and the +/// symbol's art holds a copy of the text the frame shows. +#[test] +fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() { + for command in ["symbol.new", "symbol.update"] { + let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0); + let shown = frames.map(|id| text(&s, id)); + let name = if command == "symbol.update" { + let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap()); + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + "Mark" + } else { + "Story" + }; + s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap(); + let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap(); + assert!(r["id"].is_null(), "{command}: {r}"); + assert_eq!(threads(&s), [frames], "{command}: the thread is as it was"); + assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text"); + assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows"); + } +} + /// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the /// mask art too. #[test] diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 897cd87c55..498982a7f9 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Save for Web Preview", [], None, - "{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}", + "{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}", has_doc, preview ), @@ -331,8 +331,14 @@ pub struct ColorTable { /// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the /// table when the first color was deleted. Empty: the reduction makes the palette. pub custom_palette: Vec, + /// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A + /// shifted color is locked, and a source the table does not hold shifts nothing. + pub shifted: std::collections::BTreeMap, } +/// A color shifted by hand: (source, color written). +type Shift = ([u8; 3], [u8; 3]); + /// The most colours a colour table list holds. const MAX_TABLE: usize = 256; @@ -352,6 +358,21 @@ impl ColorTable { list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect() } + /// The colors shifted by hand as (source, color written). An error names a value that is not a + /// color such as `#ff8800`, two keys that name one color, or more than 256 entries. + fn shifts(&self) -> std::result::Result, String> { + // One entry past the limit is enough for `colors` to refuse a longer map. + let (keys, values): (Vec, Vec) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip(); + let sources = Self::colors(&keys, "shifted")?; + let to = Self::colors(&values, "shifted")?; + for (i, (s, k)) in sources.iter().zip(&keys).enumerate() { + if sources[..i].contains(s) { + return Err(format!("colorTable.shifted: `{k}` names a color another key names")); + } + } + Ok(sources.into_iter().zip(to).collect()) + } + /// `h` as RGB; `None` when it is not a color such as `#ff8800`. fn rgb(h: &str) -> Option<[u8; 3]> { vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| { @@ -487,13 +508,18 @@ impl WebSettings { { ColorTable::colors(list, what)?; } - // A deleted color is no longer locked, transparent or web-shifted. + // A deleted color is no longer locked, transparent, web-shifted or shifted. let deleted = ColorTable::colors(&table.deleted, "deleted")?; if !deleted.is_empty() { for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] { list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c))); } } + // Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and + // a color shifted by hand is not web-shifted. + let shifts: Vec = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect(); + table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c))); + table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect(); Ok(self) } @@ -640,6 +666,8 @@ pub struct TableColor { pub transparent: bool, pub locked: bool, pub web_shifted: bool, + /// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`. + pub shifted: bool, } /// An optimised image file. @@ -759,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 let locked = ColorTable::colors(&table.locked, "locked")?; let to_clear = ColorTable::colors(&table.transparent, "transparent")?; let shift = ColorTable::colors(&table.web_shift, "webShift")?; + let by_hand = table.shifts()?; + let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to); + // A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes + // one of the slots kept for them before the locked colors do. + let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect(); let o = PaletteOptions { colors: s.colors, reduction: s.reduction, @@ -767,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 transparency: s.transparency, matte, }; - let mut ix = reduced(rgba, w, h, s, &o, &locked)?; + let mut ix = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. let before = ix.palette.clone(); let clear = ix.transparent.map(usize::from); @@ -781,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 *slot = *c; } } - // Web snap, then the colours shifted by hand (locked colours stay as they are). + // Web shift and web snap (locked colors and colors shifted by hand stay as they are). let clear = ix.transparent.map(usize::from); for (i, c) in ix.palette.iter_mut().enumerate() { let src = sources.get(i).copied().unwrap_or(*c); - if Some(i) == clear || locked.contains(&src) { + if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) { continue; } if shift.contains(&src) { @@ -794,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 *c = snapped; } } + // Lossy compares the pixels with the colors written for them, and moves no pixel into or out of + // a color shifted by hand. if s.format == WebFormat::Gif { - web::lossy(&mut ix, rgba, s.lossy); + let fixed: Vec = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect(); + web::lossy(&mut ix, rgba, s.lossy, &fixed); + } + // The colors shifted by hand. + for (i, c) in ix.palette.iter_mut().enumerate() { + if Some(i) != clear + && let Some(to) = sources.get(i).and_then(shifted_to) + { + *c = to; + } } let order = web::sort(&mut ix, table.sort); let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect(); @@ -804,12 +848,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 .iter() .zip(&sources) .enumerate() - .map(|(i, (c, src))| TableColor { - color: *c, - source: *src, - transparent: ix.transparent == u8::try_from(i).ok(), - locked: locked.contains(src), - web_shifted: shift.contains(src), + .map(|(i, (c, src))| { + let transparent = ix.transparent == u8::try_from(i).ok(); + let shifted = !transparent && shifted_to(src).is_some(); + TableColor { + color: *c, + source: *src, + transparent, + locked: locked.contains(src) || shifted, + web_shifted: shift.contains(src) && !shifted, + shifted, + } }) .collect(); Ok(PaletteImage { ix, colors, mapped }) @@ -818,7 +867,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 /// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the /// color table's fixed one, without the deleted colors. The pixels of a deleted color take the /// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to -/// transparent. +/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of +/// `colors` together, and its first opaque colors that fit in the rest. fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result { let table = &s.color_table; let deleted = ColorTable::colors(&table.deleted, "deleted")?; @@ -847,11 +897,70 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc left.push(c); } } - left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear)); if left.is_empty() || (removed && !opaque_left(&left)) { return Err(KEEP_ONE.into()); } - Ok(quantize::quantize_to(rgba, w, h, o, &left)) + // The colors mapped to transparent all become the one transparent entry, so together they take + // one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of + // them and no pixel is transparent, that slot goes to the next opaque color instead. + let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true); + let mut ix = quantize::quantize_to(rgba, w, h, o, &kept); + clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); + if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) { + return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false))); + } + Ok(ix) +} + +/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in +/// `to_clear` are kept and take one slot together; without it they are left out. The list holds +/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry). +fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { + let any_clear = clear && left.iter().any(|c| to_clear.contains(c)); + let total = 256 - usize::from(has_clear); + let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); + let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room); + let mut clear_room = if clear { total - opaque } else { 0 }; + left.iter() + .copied() + .filter(|c| { + let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room }; + let keep = *slots > 0; + *slots = slots.saturating_sub(1); + keep + }) + .collect() +} + +/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to +/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the +/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later. +fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) { + let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect(); + if dropped.is_empty() { + return; + } + let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); + let near = quantize::nearest_entries(rgba, o, &all); + if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { + return; + } + let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) { + Some(i) => i, + None => { + // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. + let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else { + return; + }; + ix.palette.push(*c); + i + } + }; + for (v, n) in ix.indices.iter_mut().zip(&near) { + if n.is_some_and(|n| n >= kept.len()) { + *v = entry; + } + } } /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). @@ -1116,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { .map(|c| { json!({ "color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked, - "webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color, + "webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color, }) }) .collect(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7e2f995e94..de780f406c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -415,7 +415,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, Prefs}; +pub use prefs::{DrawMode, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 18afc02d1c..6d044eace3 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,26 @@ pub enum DrawMode { Inside, } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run +/// may use ([`vectorcraft_plugins::Plugin::large_limits`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PluginBudget { + /// The plug-in's own limits. + #[default] + Normal, + /// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of + /// input; the time budget is unchanged. + Large, +} + +/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the +/// other preferences are read as they are. +fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal }) +} + /// A saved Default Language as its tag: older preferences hold the language's name, and one the list /// no longer has reads as the default. fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { @@ -179,6 +199,11 @@ pub struct Prefs { pub fonts_folder: String, // Plug-ins & Scratch Disks pub plugins_folder: String, + /// Plug-in Instruction Budget: the instructions each object filter run gets, from + /// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers + /// keep their own budgets. + #[serde(deserialize_with = "plugin_budget")] + pub plugin_instruction_budget: PluginBudget, pub scratch_primary: String, pub scratch_secondary: String, // User Interface @@ -496,6 +521,7 @@ impl Default for Prefs { hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), + plugin_instruction_budget: PluginBudget::Normal, scratch_primary: s("Startup"), scratch_secondary: s("None"), ui_brightness: s("mediumDark"), diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 4f0b739951..f960ca91d3 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -110,6 +110,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "art-ribbons", "ink-and-wash", "calligraphic-nibs", + "pressure-sensitive", "bristle-brushes", "pattern-borders", "scatter-shapes", @@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[6]["count"].as_u64(), Some(4)); + assert_eq!(libs[7]["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[7]["count"].as_u64(), Some(4)); + assert_eq!(libs[8]["count"].as_u64(), Some(4)); let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); assert_eq!( dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); - assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4))); + assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); @@ -154,6 +155,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("art-ribbons", "art"), ("ink-and-wash", "art"), ("calligraphic-nibs", "calligraphic"), + ("pressure-sensitive", "art"), ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), @@ -164,7 +166,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); for b in &lib.brushes { - let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind }; + let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind }; assert_eq!(b.kind.type_id(), kind, "{}", b.name); let mut line = vectorcraft_geom::BezPath::new(); line.move_to((0.0, 0.0)); @@ -299,6 +301,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap(); + let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut curve = line_to(20.0); + curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0)); + for b in &lib.brushes { + let width_at = |pressure| { + let stroke = vectorcraft_doc::StrokeLayer { + pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), + ..black_stroke() + }; + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name); + let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max); + max - min + }; + let light = width_at(0.0); + let heavy = width_at(1.0); + for width in [light, heavy] { + assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name); + } + assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name); + for line in [line_to(2.0), curve.clone()] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke()); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two /// translucent washes, with names of their own and a few paths of art each. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 6d42e080a9..3a3a07a2c1 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -2274,6 +2274,93 @@ fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() } } +/// The number of symbol instances in the document. +fn instance_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }))); + n +} + +/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current +/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the +/// result has no instance id and nothing places the symbol. One undo step takes the symbol away +/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance. +#[test] +fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() { + let mut s = session(); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i)); + let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)); + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[a, b]); + let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap(); + assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}"); + assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected"); + assert_eq!(instance_count(&s), 0, "no instance"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0))); + // The symbol's art is the pair: an instance placed from it is 120 × 50. + let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap()); + let w = bounds(&s, placed); + assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away"); + assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo"); + assert_eq!(instance_count(&s), 0, "redo places no instance"); + // false, like no keepArt, makes the art an instance. + for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] { + let r = s.execute("symbol.new", &p).unwrap(); + let id = NodeId(r["id"].as_u64().expect("an instance id")); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}"); + } + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none()); +} + +/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it +/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the +/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and +/// no undo step. +#[test] +fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() { + let mut s = session(); + let (inst, _, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(locked).unwrap().locked = true; + doc.node_mut(hidden).unwrap().visible = false; + } + for bad in [json!("true"), json!(1), json!([true])] { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err(); + assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step"); + } + select(&mut s, &[]); + let symbols = s.doc().unwrap().doc.symbols.len(); + let ids = [a.0, locked.0, hidden.0, inst.0]; + s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1); + let selected = &s.doc().unwrap().selection.objects; + assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}"); + for id in [a, locked, hidden] { + assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art"); + } + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance"); + assert_eq!(instance_count(&s), 1, "no new instance"); +} + /// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a /// group, in an opacity mask, or through the art of another symbol it holds an instance of, and /// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 4e8d8697d4..b9a90f55c7 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -387,22 +387,79 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115; +/// the fill's shape is 9 pt larger on each side. +fn image_with_shaped_fill(s: &mut Session) -> NodeId { + 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(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [im.0]})); + run(s, "appearance.addFill", json!({})); + run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); + run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + im +} + +/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in +/// outline with `outline`. +fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec { + let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0); + vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false) +} + +/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its +/// art outside its box, as a click there selects it, except in outline. +#[test] +fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), []); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill"); + assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill"); + assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is"); + + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke"); + assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art"); +} + +/// A marquee touches an image where the shape of its own fill lies outside its frame, and an +/// instance of a symbol made of that image where the instance's fill effect grows that shape, as +/// clicks there select them, except in outline. +#[test] +fn a_marquee_on_the_shape_of_an_image_fill_selects_it() { + let mut s = session(); + let im = image_with_shaped_fill(&mut s); + assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame"); + assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape"); + assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame"); + + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill"); + assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill"); +} + /// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill /// effect grows what that fill paints, and a click there selects the instance. #[test] fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() { 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(); - // The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side. - let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); - let im = NodeId(r["ids"][0].as_u64().unwrap()); - run(&mut s, "select.set", json!({"ids": [im.0]})); - run(&mut s, "appearance.addFill", json!({})); - run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); - run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + image_with_shaped_fill(&mut s); let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); let row = node(&s, id).appearance.items.len() - 1; diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index e5483d1889..582543f7eb 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_ assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); } +/// A confined request packages no linked file whose native document it can't read to check against +/// its read roots: a PDF that needs a password to open, and a native document that doesn't load, +/// even inside the roots. The package is refused before anything is written, with an error that +/// names no file or folder. A PDF without editing data is copied, and the person's package copies +/// every file. +#[test] +fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() { + let home = Folder::new("package-unreadable-home"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let out = home.file("out"); + let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)); + let refused = |s: &mut Session, p: Value| { + let e = package(s, p.clone()).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}"); + assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}"); + assert!(!std::path::Path::new(&out).exists(), "{p}"); + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + let pdf = home.file("art/part.pdf"); + save(&mut part, &native); + let pdf_of = + |part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap(); + let editable = pdf_of(&mut part, json!({"format": "pdf"})); + let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}})); + assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data"); + let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false})); + let poster = |placed: &str| { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + s + }; + write(&pdf, &editable); + let mut s = poster(&pdf); + write(&pdf, &locked); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + // A package prepared in the confined request and written on another thread. + let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap(); + let e = + std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused"); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}"); + assert!(!std::path::Path::new(&out).exists()); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF listing the editing file without its data (`EF` renamed, the same length). + let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF"); + let mut detached = editable.clone(); + detached[at..at + 3].copy_from_slice(b"/XF"); + assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved"); + write(&pdf, &detached); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF without editing data. + write(&pdf, &plain); + assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); + std::fs::remove_dir_all(&out).unwrap(); + // A PDF whose attachments are too many to search to their end, with a readable editing file + // listed before the ones left unsearched. + let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data); + assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read"); + write(&pdf, &cut); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A native document that doesn't load, rewritten or copied as it is. + let mut s = poster(&native); + write(&native, b"not a document"); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"folder": out, "relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); +} + +/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree +/// whose second subtree has 70,000 nodes, more than are searched. +fn attachments_cut_short(native: &[u8]) -> Vec { + let name = vectorcraft_pdf::EDITING_FILE; + let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes(); + stream.extend_from_slice(native); + stream.extend_from_slice(b"\nendstream"); + let objects = [ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(), + b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(), + format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(), + format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(), + stream, + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, body) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); + for at in &offsets { + out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); + out +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 63dbde37a6..947a3ec42d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() { assert_eq!(s.doc().unwrap().doc, before); } +/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter +/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as +/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's +/// larger budget stay as they are, and setting Normal again applies to the next run. +#[test] +fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() { + use cmd::plugin::FilterRun; + let mut s = session(); + let id = "test.engine.largebudget"; + let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string(); + // More steps than a light budget pays for, fewer than 5 times it. + install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output)); + let p = json!({"id": id, "ids": []}); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"})); + let light = vectorcraft_plugins::Limits::default(); + let large = FilterRun::prepare(&s, &p).unwrap().limits().clone(); + assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() }); + assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms)); + // Cancel still stops it, and it changes nothing. + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p)); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + let made = run(&mut s, "plugin.run", p.clone())["ids"].clone(); + assert_eq!(made.as_array().map(Vec::len), Some(1)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + // A heavy filter keeps its larger budget with either choice. + let heavy_id = "test.engine.largebudget.heavy"; + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true})); + let hp = json!({"id": heavy_id, "ids": []}); + for budget in ["large", "normal"] { + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget})); + let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone(); + let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS); + assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}"); + } + + // Normal again: the next run runs out of instructions. + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": heavy_id})); +} + /// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list). fn with_commands(id: &str, kind: &str, commands: &str) -> String { format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#) diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 94a5a1f12e..966e68dc60 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -464,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() { assert_eq!(s.prefs.gpu_preference, "automatic"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or +/// label, kept through a save and load, and reset with its category. Setting another value is an +/// error that changes nothing; a saved value that is missing, unknown or of another type reads as +/// Normal and leaves the other saved preferences as they are. +#[test] +fn plugin_instruction_budget_defaults_to_normal_and_validates() { + let mut s = Session::new(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal")); + set_pref(&mut s, "pluginInstructionBudget", json!("Large")); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large")); + for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] { + assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}"); + } + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.plugin_instruction_budget, PluginBudget::Large); + let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")]; + let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v})); + for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) { + let read: Prefs = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}"); + } + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone(); + assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins"))); + assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large"))); + s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); +} + /// Performance › Low-Latency Drawing (#6013): off by default and for preference files written /// before it, a boolean only, kept through a save/load round trip, listed under Performance and /// reset with it. diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 6f0242c662..dd5ca1d9f8 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() { assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance)); } +/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id, +/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as +/// they are, in one undo step. A style replaced by itself or by a style with the same look records +/// nothing, and bad parameters are errors that change nothing. +#[test] +fn redefine_from_a_style_gives_the_style_that_look() { + let mut s = session(); + let (a, b, c) = linked_three(&mut s); + let d = rect(&mut s, 300.0); + set_fill(&mut s, d, "#0000ff"); + run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"})); + run(&mut s, "graphicStyle.new", json!({"name": "Blue"})); + set_fill(&mut s, c, "#00ff00"); + let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s)); + assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S"); + assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() }); + assert_eq!(names(&s), order); + let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for id in [a, b] { + let n = node(&s, id); + assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply)); + } + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + // The edited object keeps its look and is unlinked; Blue and its object are as they were. + assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert_eq!(node(&s, c).extras().graphic_style, None); + assert_eq!(style(&s, "Blue"), blue); + assert_eq!(linked(&mut s, "Blue"), vec![d.0]); + let step = s.doc().unwrap().history.undo.last().unwrap().clone(); + assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(style(&s, "S"), old); + assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE))); + assert_eq!(node(&s, c).extras().graphic_style, Some(old.id)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(style(&s, "S").appearance, blue.appearance); + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + run(&mut s, "edit.undo", json!({})); + + // A style replaced by itself, or by a copy with the same look, records nothing. + run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"})); + let before = steps(&s); + run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"})); + run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"})); + assert_eq!(steps(&s), before); + assert_eq!(style(&s, "S"), old); + + // A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors. + for p in [ + json!({"name": "S", "from": "nope"}), + json!({"name": "nope", "from": "Blue"}), + json!({"name": "S", "from": 3}), + json!({"name": "S", "from": "Blue", "id": a.0}), + json!({"from": "Blue"}), + ] { + assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}"); + } + assert_eq!((steps(&s), style(&s, "S")), (before, old)); +} + #[test] fn deleting_a_style_unlinks_and_renaming_keeps_links() { let mut s = session(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 21ae0796d3..fe3deecbef 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -539,6 +539,196 @@ fn colour_table_delete_maps_pixels_to_the_nearest_color_left() { assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]); } +/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the +/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the +/// pixels of the colors mapped to transparent become transparent. +#[test] +fn colour_table_fixed_palette_keeps_an_opaque_color() { + // 40×10: red, a near red and blue, and 10 px with nothing (transparent). + let mut s = session(40.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + for table in [ + json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}), + json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}), + ] { + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table}); + let v = run(&mut s, "document.exportForWeb.preview", p.clone()); + let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect(); + assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}"); + let img = pixels(&one(&mut s, p.clone())); + let alpha = |x: u32| img.get_pixel(x, 5).0[3]; + assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}"); + } + // A color mapped to transparent that no pixel takes leaves its slot to an opaque color. + let mut u = session(20.0, 10.0); + rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00"); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}}); + let img = pixels(&one(&mut u, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255])); + // At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry. + let full: Vec = + std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0)); + // With one opaque color and 255 mapped to transparent, the last of those does not fit, and its + // pixels still become transparent rather than taking the opaque color nearest them. + let mut d = session(30.0, 10.0); + rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee"); + let clear: Vec = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect(); + let palette: Vec = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}}); + let img = pixels(&one(&mut d, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0)); + // Without transparent pixels the colors mapped to transparent still take one slot together. + let mut t = session(30.0, 10.0); + rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": { + "customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"], + }}); + let v = run(&mut t, "document.exportForWeb.preview", p.clone()); + assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}"); + let img = pixels(&one(&mut t, p)); + assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255])); +} + +/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in +/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is +/// the file. +#[test] +fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00"); + let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p); + let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}}); + let v = preview(&mut s, p.clone()); + let c = entry(&v, "#0000ff"); + assert_eq!( + (c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()), + (Some("#ff8800"), Some(true), Some(true), Some(false)), + "{format}: {v}" + ); + assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000"))); + let file = one(&mut s, p); + assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file"); + let img = pixels(&file); + assert_eq!( + (img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0), + ([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]), + "{format}" + ); + assert_eq!(distinct(&img), 3, "{format}"); + } + // A shifted color is kept when the colors are reduced, as a locked one is. + let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}})); + assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}"); + // With one slot to keep, the shifted color takes it before a locked one. + let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}}); + let first = preview(&mut s, p); + assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}"); + // A source the table does not hold shifts nothing, and the shift stays with the settings. + let base = preview(&mut s, json!({"dither": "none"})); + let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}})); + assert_eq!(absent["colors"], base["colors"]); + // Two colors may be shifted to one color and keep their own sources. + let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}})); + assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456"))); + assert_eq!(entry(&same, "#00ff00")["shifted"], false); + // A shift by hand wins over web shift, web snap and a lock; transparency wins over it. + let p = + json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}}); + let c = entry(&preview(&mut s, p), "#0000ff"); + assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true))); + let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}}); + let v = preview(&mut s, clear.clone()); + assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}"); + assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0); + // The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and + // the web shift of a color shifted by hand. + let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]}); + let r = run(&mut s, "webExport.settings", json!({ "colorTable": table })); + let t = &r["settings"]["colorTable"]; + assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([]))); + // Another reduction keeps the shifts; a saved preset keeps them. + let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"})); + assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"})); + run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}})); + assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101"); + // Bad shifts are refused and change nothing. + let many: serde_json::Map = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect(); + for bad in [ + json!({"nope": "#000000"}), + json!({"#ff0000": "nope"}), + json!({"#ff0000": "#ff000080"}), + json!({"#ff000080": "#000000"}), + json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}), + json!({"#f00": "#000000", "#ff0000": "#ffffff"}), + Value::Object(many), + ] { + let p = json!({"colorTable": {"shifted": bad}}); + assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}"); + assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}"); + assert!(s.execute("webExport.settings", &p).is_err(), "{p}"); + } + assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"})); + // Settings saved before shifts existed still read. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap(); + assert!(old.color_table.shifted.is_empty()); +} + +/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near +/// another one does not take in that color's pixels. +#[test] +fn lossy_does_not_spread_a_shifted_color_into_another() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000"); + let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255])); +} + +/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to +/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels. +#[test] +fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff"); + rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6"); + let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}}); + let img = pixels(&one(&mut s, p)); + let near_blue = [20, 20, 230, 255]; + for x in 0..30 { + let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue }; + assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}"); + } +} + +/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not +/// take a color that snaps far from it. +#[test] +fn lossy_compares_pixels_with_the_snapped_colors() { + let mut s = session(20.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000"); + let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50}))); + for x in 0..20 { + let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] }; + assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}"); + } +} + #[test] fn presets_and_remembered_settings() { let mut s = two_colours(); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index a17f61790e..a3470617a7 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -515,6 +515,69 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}"); } +/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant +/// opposite ways, and 120 and 300 slant as -60 does. +#[test] +fn shear_angles_slant_by_their_tangent() { + let run = 100.0 * 60f64.to_radians().tan(); + for (angle, want) in [ + (60.0, Rect::new(-run, 0.0, 100.0, 100.0)), + (-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)), + ] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap(); + assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a)); + } +} + +/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no +/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded. +#[test] +fn shear_rejects_angles_with_no_shear_or_out_of_range() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let n = undo_len(&s); + let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear"); + let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}"); + for (angle, msg) in [ + (90.0, none(90.0)), + (-90.0, none(-90.0)), + (270.0, none(270.0)), + (-270.0, none(-270.0)), + (90.0 + 1e-12, none(90.0 + 1e-12)), + (360.0, range(360.0)), + (-359.5, range(-359.5)), + (1e300, range(1e300)), + ] { + let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string()); + assert_eq!(e.to_string(), msg); + } + assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle"); + assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n, "no undo step"); +} + +/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact +/// coordinates and no undo step is recorded. +#[test] +fn shear_by_0_and_180_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let before = bounds(&s, a); + let n = undo_len(&s); + for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] { + for axis in ["horizontal", "vertical"] { + s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap(); + assert_eq!(bounds(&s, a), before, "{angle} {axis}"); + assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step"); + } + } +} + /// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point /// slides along the axis by the tangent of the shear angle times its distance across the axis /// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again diff --git a/crates/engine/tests/blend_render_consistency.rs b/crates/engine/tests/blend_render_consistency.rs new file mode 100644 index 0000000000..fdc2fb3b93 --- /dev/null +++ b/crates/engine/tests/blend_render_consistency.rs @@ -0,0 +1,200 @@ +//! Blend edits invalidate every pixel they change, including keys aligned to a curved spine. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{Document, NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Affine; +use vectorcraft_render::{Changed, RenderOptions, Rendered, Renderer, view_pixels}; + +const WIDTH: u32 = 720; +const HEIGHT: u32 = 480; + +type Retained = (Renderer, Option<(Arc, Vec)>); + +fn live(s: &Session, blend: NodeId, keys: [NodeId; 2], curved: bool) { + let doc = &s.doc().unwrap().doc; + let NodeKind::Blend { children, spec } = &doc.node(blend).unwrap().kind else { + panic!("INPUT: the fixture must remain a live blend"); + }; + assert_eq!(children.iter().map(|n| n.id).collect::>(), keys.to_vec()); + assert_eq!(serde_json::to_value(spec).unwrap()["spacing"], json!({"steps": 3})); + for key in keys { + assert_eq!(doc.parent_of(key), Some(blend), "INPUT: key identity/parent changed"); + } + if curved { + let bounds = spec.spine.as_ref().expect("INPUT: Replace Spine did not set a spine").bounds().unwrap(); + assert!(!spec.no_spine && bounds.height() > 40.0 && bounds.width() > 250.0, "INPUT: a real curved spine is required"); + } +} + +fn fixture() -> (Session, NodeId, [NodeId; 2]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap(); + let mut rectangle = |x: f64, color: &str| { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 120.0, "width": 64.0, "height": 48.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + id + }; + let keys = [rectangle(90.0, "#d52c38"), rectangle(430.0, "#25b453")]; + let blend = NodeId( + s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(), + ); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + live(&s, blend, keys, false); + (s, blend, keys) +} + +fn cpu() -> Renderer { + let mut renderer = Renderer::new(); + renderer.threads = 0; + renderer +} + +fn same_pixels(actual: &Rendered, expected: &Rendered) { + assert_eq!((actual.width, actual.height), (WIDTH, HEIGHT)); + assert_eq!((expected.width, expected.height), (WIDTH, HEIGHT)); + assert_eq!(actual.pixels.len(), (WIDTH * HEIGHT * 4) as usize); + assert!(actual.pixels == expected.pixels, "complete RGBA frames differ"); +} + +fn damage_pixels(stage: &str, changed: Changed, before: &[u8], current: &[u8]) { + let region = match changed { + Changed::Everything => return, + Changed::Nothing => None, + Changed::Area(area) => view_pixels(area, Affine::IDENTITY, WIDTH, HEIGHT), + }; + assert_eq!(before.len(), current.len()); + for (i, (old, new)) in before.as_chunks::<4>().0.iter().zip(current.as_chunks::<4>().0.iter()).enumerate() { + let (x, y) = (i as u32 % WIDTH, i as u32 / WIDTH); + if !region.is_some_and(|[x0, y0, x1, y1]| x >= x0 && x < x1 && y >= y0 && y < y1) { + assert_eq!(old, new, "{stage}: pixel ({x}, {y}) changed outside {changed:?}, view pixels {region:?}"); + } + } +} + +fn frame(s: &Session, retained: &mut Retained, stage: &str) -> Rendered { + let doc = &s.doc().unwrap().doc; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..Default::default() }; + // Ask for the edit's advertised damage before rendering the new full frame on this renderer. + let changed = retained.1.as_ref().map(|(old, _)| retained.0.changed(old.as_ref(), doc.as_ref(), &opts)); + let actual = retained.0.render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts); + let expected = cpu().render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts); + same_pixels(&actual, &expected); + let red = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] > 150 && p[1] < 100 && p[2] < 120 && p[3] == 255).count(); + let green = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] < 100 && p[1] > 120 && p[2] < 150 && p[3] == 255).count(); + assert!(red > 100 && green > 100, "INPUT: both original colored keys must really draw: red={red}, green={green}"); + if let (Some((_, previous)), Some(changed)) = (&retained.1, changed) { + damage_pixels(stage, changed, previous, &expected.pixels); + } + retained.1 = Some((doc.clone(), expected.pixels)); + actual +} + +fn move_and_undo(s: &mut Session, retained: &mut Retained, blend: NodeId, keys: [NodeId; 2], curved: bool, before_frame: &Rendered) { + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + s.execute("object.transform", &json!({"matrix": [1.0, 0.0, 0.0, 1.0, 37.0, 29.0]})).unwrap(); + live(s, blend, keys, curved); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let moved = frame(s, retained, "moved"); + assert!(moved.pixels != before_frame.pixels, "INPUT: the fresh rendered fixture must actually move"); + s.execute("edit.undo", &json!({})).unwrap(); + live(s, blend, keys, curved); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let restored = frame(s, retained, "undo-move"); + same_pixels(&restored, before_frame); +} + +#[test] +fn blend_5179_straight_move_undo_matches_fresh_cpu() { + let (mut s, blend, keys) = fixture(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "warm"); + move_and_undo(&mut s, &mut retained, blend, keys, false, &warm); +} + +#[test] +fn blend_5179_replace_spine_move_undo_matches_fresh_cpu() { + let (mut s, blend, keys) = fixture(); + let path = NodeId(s.execute("path.create", &json!({"d": "M122 144 C166 330 402 288 462 144"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap(); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + let nodes = s.doc().unwrap().doc.node_count(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "before-replace"); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + live(&s, blend, keys, true); + assert!(s.doc().unwrap().doc.node(path).is_none(), "Replace Spine consumes the original standalone path"); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes - 1); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let replaced = frame(&s, &mut retained, "replaced"); + assert!(replaced.pixels != warm.pixels, "INPUT: replacing the spine must visibly change the drawn fixture"); + move_and_undo(&mut s, &mut retained, blend, keys, true, &replaced); + s.execute("edit.undo", &json!({})).unwrap(); + live(&s, blend, keys, false); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + let restored = frame(&s, &mut retained, "undo-replace"); + same_pixels(&restored, &warm); +} + +// A fixed ordinary anisotropic Transform, evaluated after Align to Path turns the key. +// 200% is the legitimate control; 400% is the single source-derived witness. +fn rotated_transform_damage(scale_h: f64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap(); + let mut rectangle = |x: f64, color: &str| { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 200.0, "width": 8.0, "height": 80.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": scale_h, "scaleV": 100.0, "reference": 4}})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 8.0).abs() < 1e-8 && (b.height() - 80.0).abs() < 1e-8, "INPUT: the Transform must remain live on the narrow key"); + assert_eq!(n.appearance.effects.len(), 1); + assert_eq!(n.appearance.effects[0].params["scaleH"], json!(scale_h)); + id + }; + let keys = [rectangle(260.0, "#d52c38"), rectangle(460.0, "#25b453")]; + let blend = NodeId( + s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(), + ); + live(&s, blend, keys, false); + let path = NodeId(s.execute("path.create", &json!({"d": "M264 160 L264 320"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap(); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "anisotropic-before-replace"); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + live(&s, blend, keys, false); + assert!(s.doc().unwrap().doc.node(path).is_none()); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let n = s.doc().unwrap().doc.node(blend).unwrap(); + let NodeKind::Blend { spec, .. } = &n.kind else { panic!("INPUT: the fixture must remain a live blend") }; + let spine = spec.spine.as_ref().unwrap().bounds().unwrap(); + assert!(spine.width().abs() < 1e-8 && (spine.height() - 160.0).abs() < 1e-8, "INPUT: this is the fixed vertical rail"); + let expanded = vectorcraft_render::expand_live(n); + let placed = expanded.iter().find(|n| n.id == keys[0]).unwrap(); + let b = placed.geometric_bounds().unwrap(); + assert!((b.width() - 80.0).abs() < 1e-8 && (b.height() - 8.0).abs() < 1e-8, "INPUT: Align to Path must really turn the key by 90 degrees"); + assert_eq!(placed.appearance.effects.len(), 1); + assert_eq!(placed.appearance.effects[0].params["scaleH"], json!(scale_h)); + let replaced = frame(&s, &mut retained, &format!("rotated-transform-{scale_h}-replace")); + assert!(replaced.pixels != warm.pixels, "INPUT: the replacement must really change the painted frame"); + move_and_undo(&mut s, &mut retained, blend, keys, false, &replaced); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + let restored = frame(&s, &mut retained, "anisotropic-undo-replace"); + same_pixels(&restored, &warm); +} + +#[test] +fn blend_5179_rotated_transform_damage_contains_painted_pixels() { + // The control completes every render, move and history check before the witness runs. + rotated_transform_damage(200.0); + rotated_transform_damage(400.0); +} diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 94c54dea4f..17391ae98a 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() { assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension"); } +#[test] +fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() { + use vectorcraft_doc::Arrowhead; + let mut s = session(); + for (style, head) in + [("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)] + { + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let heads: Vec<_> = n + .children() + .unwrap() + .iter() + .filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))) + .filter(|(a, b)| a.is_some() || b.is_some()) + .collect(); + match head { + Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"), + None => assert!(heads.is_empty(), "{style}: {heads:?}"), + } + } +} + #[test] fn dimension_angles_circles_arcs_and_curves() { let mut s = session(); @@ -1933,6 +1956,149 @@ fn an_anchor_beside_a_drawn_dimension_takes_the_point() { assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()])); } +/// The Smart Guide lines a pointer move at (`x`, `y`) shows, as their ends. +fn guide_lines(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> Vec<(vectorcraft_geom::Point, vectorcraft_geom::Point)> { + use vectorcraft_engine::tools::Overlay; + s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap(); + s.overlays(view).into_iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some((a, b)) } else { None }).collect() +} + +/// An edge with anchors at x 100, 200 and 300, and a dimension from 100 to 200 placed 30 points +/// above it, with the Dimension tool active and nothing selected: the session and the dimension. +fn level_start(view: ViewInfo) -> (Session, u64) { + let pt = vectorcraft_geom::Point::new; + let mut s = session(); + run(&mut s, "path.create", json!({"d": "M100 200 L200 200 L300 200 L300 300 L100 300 Z"})); + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", view).unwrap(); + linear_click(&mut s, view, 100.0, 200.0); + linear_click(&mut s, view, 200.0, 200.0); + linear_click(&mut s, view, 150.0, 170.0); + let first = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + run(&mut s, "select.none", json!({})); + (s, first) +} + +/// The next dimension, from 200 to 300, placed with the pointer at `y`: where its line lies. +fn level_next(s: &mut Session, view: ViewInfo, y: f64) -> (vectorcraft_geom::Point, vectorcraft_geom::Point) { + linear_click(s, view, 200.0, 200.0); + linear_click(s, view, 300.0, 200.0); + linear_click(s, view, 250.0, y); + let id = s.doc().unwrap().selection.objects[0].0; + recipe(s, id).line_ends() +} + +/// A dimension placed next to another, with its line within the Smart Guides snapping tolerance of +/// the level of the other's parallel line, has its line on that level. A level further off, Smart +/// Guides off, a locked dimension or one that is not parallel leaves the line where the pointer +/// puts it. +#[test] +fn a_dimension_line_placed_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let off = ViewInfo { smart_guides: false, ..plain }; + let pt = vectorcraft_geom::Point::new; + // 2.5 points below the first line's level, and 3.5 above it: on the level. + for y in [172.5, 166.5] { + let (mut s, _) = level_start(plain); + assert_eq!(level_next(&mut s, plain, y), (pt(200.0, 170.0), pt(300.0, 170.0)), "pointer at y {y}"); + } + // 10 points off: where the pointer is. + let (mut s, _) = level_start(plain); + assert_eq!(level_next(&mut s, plain, 180.0), (pt(200.0, 180.0), pt(300.0, 180.0))); + // Smart Guides off: where the pointer is. + let (mut s, _) = level_start(off); + assert_eq!(level_next(&mut s, off, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); + // A locked dimension does not pull the line. + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "object.lock", json!({})); + assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); + // A dimension of the right edge has a vertical line, which is not parallel to the first: the + // pointer 2.5 points below the first line's level places it where the pointer is. + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 300.0, 200.0); + linear_click(&mut s, plain, 300.0, 300.0); + linear_click(&mut s, plain, 330.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0))); +} + +/// While a dimension is placed with its line on the level of another, one alignment guide runs +/// along the level across both lines. Off the level, after a dropped press and with Alignment +/// Guides off, no guide shows. +#[test] +fn a_dimension_line_on_another_level_shows_one_guide_across_both() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + let guides = guide_lines(&mut s, plain, 250.0, 172.5); + assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level"); + // A press on the level that the app drops cancels the preview, and its guide goes with it. + assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 172.5), plain).unwrap(); + s.drop_tool_press(plain).unwrap(); + assert!(s.overlays(plain).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(plain)); + // Alignment Guides off: the line still lands on the level, with no guide. + let (mut s, _) = level_start(plain); + run(&mut s, "prefs.set", json!({"key": "alignmentGuides", "value": false})); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + assert!(guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); + linear_click(&mut s, plain, 250.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0))); +} + +/// A second dimension of the same two points as a dimension already drawn lands on its level too. +/// Off every level, a pointer moved in small steps while it is placed puts the line at each step, +/// with no pull from the preview of the dimension itself. +#[test] +fn a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + linear_click(&mut s, plain, 100.0, 200.0); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 150.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_ne!(id, first); + assert_eq!(recipe(&s, id).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + for y in [190.0, 189.0, 188.0, 187.0, 186.0] { + s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, y), plain).unwrap(); + } + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 250.0, 186.0), plain).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 186.0), pt(300.0, 186.0))); +} + +/// A dimension dragged out from a segment, with its line within the Smart Guides snapping +/// tolerance of the level of another dimension's parallel line, lands on that level. +#[test] +fn a_dimension_dragged_out_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + // The bottom edge dragged out to 2 points below the level of the first line, 130 points + // above the edge: on the level. + let (mut s, _) = level_start(plain); + for (kind, y) in + [(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0), (PointerKind::Up, 172.0)] + { + s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0].0; + let (a, b) = recipe(&s, id).line_ends(); + assert!(near(a, pt(300.0, 170.0)) && near(b, pt(100.0, 170.0)) || near(a, pt(100.0, 170.0)) && near(b, pt(300.0, 170.0)), "{a:?} {b:?}"); +} + /// The page content streams of exported PDF `v`, inflated. fn pdf_content(v: &Value) -> String { let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index cc39566875..a8de5429dc 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -287,3 +287,107 @@ fn a_cancelled_export_stops_the_exporter() { assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); } + +/// Every string in `v`, at any depth. +fn strings_in(v: &Value, out: &mut Vec) { + match v { + Value::String(s) => out.push(s.clone()), + Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)), + Value::Object(map) => map.values().for_each(|v| strings_in(v, out)), + _ => {} + } +} + +/// A confined caller: an exporter, given the native document's JSON, is not run for a document +/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every +/// command that writes its format refuses, before any file or folder is written, with an error +/// that names no file or folder, and the document keeps its links. A data set's image inside the +/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them, +/// and the person's export gives it every path as stored. +#[test] +fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() { + use vectorcraft_engine::file_access::{AutomationRoots, confine}; + + let away = tmp_dir("confined-away"); + let home = tmp_dir("confined-home"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input)); + let format = "plugin.test.confined"; + let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap(); + let out = path_of(&home.join("out")); + let outputs = [ + ("document.serialize", json!({"format": format})), + ("document.export", json!({"format": format})), + ("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})), + ("document.exportSelection", json!({"format": format})), + ("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})), + ("assets.export", json!({"folder": out, "formats": [{"format": format}]})), + ]; + let hidden = [path_of(&away), path_of(&home)]; + // `assets`: an asset's file is checked too (its document holds the asset's art and the + // document's data sets, not other art). + let refused = |s: &mut Session, why: &str, assets: bool| { + for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") { + let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}")); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains(why), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + } + assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written"); + }; + // The strings of the JSON the exporter is given. + let given = |s: &mut Session, confined: bool| { + let p = json!({"format": format}); + let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) }; + let mut found = vec![]; + strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found); + found + }; + + let script = path_of(&away.join("menu.js")); + s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap(); + refused(&mut s, "a linked JavaScript file is outside the read roots", true); + assert!(given(&mut s, false).contains(&script), "the person's export"); + s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap(); + + let set_image = |s: &mut Session, path: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect(); + doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }]; + }; + let photo = path_of(&away.join("photo.png")); + set_image(&mut s, &photo); + refused(&mut s, "a linked image file is outside the read roots", true); + assert!(given(&mut s, false).contains(&photo), "the person's export"); + let inside = path_of(&home.join("photo.png")); + set_image(&mut s, &inside); + assert!(given(&mut s, true).contains(&inside), "an image inside the read roots"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear(); + + let folder = path_of(&away.join("screens")); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap(); + assert!(!given(&mut s, true).contains(&folder), "the export folder is left out"); + assert!(given(&mut s, false).contains(&folder), "the person's export"); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it"); + + let mut part = Session::new(); + part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = path_of(&away.join("part.vectorcraft")); + part.execute("file.saveAs", &json!({"path": placed})).unwrap(); + s.execute("file.place", &json!({"path": placed, "link": true})).unwrap(); + refused(&mut s, "a linked image file is outside the read roots", false); + // The asset's file holds the rectangle alone, without the placed file. + let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap(); + let mut found = vec![]; + strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found); + assert!(!found.contains(&placed), "{found:?}"); + let _ = std::fs::remove_dir_all(&away); + let _ = std::fs::remove_dir_all(&home); +} diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/preflight.rs new file mode 100644 index 0000000000..08b7cf153b --- /dev/null +++ b/crates/engine/tests/preflight.rs @@ -0,0 +1,216 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +//! Production preflight must find actual delivery problems and clear them after repairs. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +fn new() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({ "width": 500, "height": 400 })).unwrap(); + s +} + +fn check(s: &mut Session) -> Value { + s.execute("document.preflight", &json!({})).unwrap() +} + +fn codes(report: &Value) -> Vec<&str> { + report["findings"].as_array().unwrap().iter().map(|f| f["code"].as_str().unwrap()).collect() +} + +#[test] +fn preflight_finds_four_problems_and_repairs_clear_each_one() { + let dir = Folder::new("preflight-four"); + let path = dir.file("picture.png"); + let bytes = png(40, 40, [200, 50, 10]); + std::fs::write(&path, &bytes).unwrap(); + let mut s = new(); + let text = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight Missing Family 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone(); + let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200], "link": true })).unwrap()["ids"][0].clone(); + std::fs::remove_file(&path).unwrap(); + let before_doc = s.doc().unwrap().doc.clone(); + let before_sel = s.doc().unwrap().selection.clone(); + let revision = s.doc().unwrap().revision; + let report = check(&mut s); + for code in ["missingFont", "overflow", "missingLink", "lowResolution"] { + assert!(codes(&report).contains(&code), "{code}: {report}"); + } + assert_eq!(*before_doc, *s.doc().unwrap().doc); + assert_eq!(before_sel, s.doc().unwrap().selection); + assert_eq!(revision, s.doc().unwrap().revision, "checking doesn't edit the document"); + for f in report["findings"].as_array().unwrap() { + assert!(f["ids"].as_array().unwrap().iter().all(|id| id == &text || id == &image), "{f}"); + } + s.execute("text.areaOptions", &json!({ "ids": [text], "height": 150 })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"overflow")); + std::fs::write(&path, &bytes).unwrap(); + s.execute("links.update", &json!({ "ids": [image] })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"missingLink")); + s.execute("select.set", &json!({ "ids": [image] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 7.2, "height": 7.2 })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"lowResolution")); + // Deleting the missing-font object fixes the final delivery issue on any machine, including + // builds with no optional craft-fonts checkout or installed fonts. + s.execute("select.set", &json!({ "ids": [text] })).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let clean = check(&mut s); + assert!(codes(&clean).is_empty(), "{clean}"); + assert!(clean["checks"].as_array().unwrap().iter().all(|c| c["status"] == "passed")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(codes(&check(&mut s)).contains(&"missingFont"), "undo is checked too"); +} + +#[test] +fn preflight_reuses_link_probes_for_external_changes_without_an_edit() { + let dir = Folder::new("preflight-modified"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap(); + let mut s = new(); + let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200] })).unwrap()["ids"][0].clone(); + let rev = s.doc().unwrap().revision; + std::fs::write(&path, png(41, 45, [10, 50, 200])).unwrap(); + assert!(codes(&check(&mut s)).contains(&"modifiedLink")); + assert_eq!(rev, s.doc().unwrap().revision); + s.execute("links.update", &json!({ "ids": [image] })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"modifiedLink")); +} + +#[test] +fn preflight_scopes_artboards_and_respects_hidden_and_nonprinting_layers() { + let mut s = new(); + let id = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Scope 917" })).unwrap()["id"].clone(); + s.execute("artboard.new", &json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap(); + let other = s.execute("document.preflight", &json!({ "artboards": [1] })).unwrap(); + assert!(codes(&other).is_empty(), "{other}"); + assert!(codes(&check(&mut s)).contains(&"missingFont")); + s.execute("object.setProps", &json!({ "ids": [id], "visible": false })).unwrap(); + assert!(codes(&check(&mut s)).is_empty()); + s.execute("object.setProps", &json!({ "ids": [id], "visible": true, "locked": true })).unwrap(); + assert!(codes(&check(&mut s)).contains(&"missingFont"), "locked artwork still exports"); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.setProps", &json!({ "id": layer.0, "printable": false })).unwrap(); + let print = s.execute("document.preflight", &json!({ "output": "print" })).unwrap(); + assert!(codes(&print).is_empty(), "{print}"); +} + +#[test] +fn preflight_resolution_follows_placed_size_and_both_axes() { + let dir = Folder::new("preflight-resolution"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone(); + s.execute("select.set", &json!({ "ids": [id] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 72 })).unwrap(); + let r = check(&mut s); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["effectivePpi"], json!([300.0, 100.0])); + let screen = s.execute("document.preflight", &json!({ "output": "screen" })).unwrap(); + assert_eq!(screen["minPpi"], 96.0); + assert!(codes(&screen).is_empty(), "{screen}"); +} + +#[test] +fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() { + let dir = Folder::new("preflight-resolution-boundary"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap(); + let mut s = new(); + s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap(); + for threshold in [31.0, 59.0, 300.0, 600.0, 9600.0] { + let size = 40.0 * 72.0 / threshold; + s.execute("object.setBounds", &json!({ "width": size, "height": size })).unwrap(); + let exact = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap(); + assert!(!codes(&exact).contains(&"lowResolution"), "exactly {threshold} ppi: {exact}"); + s.execute("object.setBounds", &json!({ "width": size * 1.000001, "height": size })).unwrap(); + let below = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap(); + let f = below["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["threshold"], threshold); + } +} + +#[test] +fn preflight_resolution_includes_the_print_jobs_scale() { + let dir = Folder::new("preflight-print-scale"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + s.execute("file.place", &json!({ "path": path, "link": false, "at": [250, 200] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap(); + let doc = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap(); + assert!(codes(&doc).is_empty(), "{doc}"); + s.execute("print.setup", &json!({ "settings": { "scaling": "custom", "scale": { "width": 200, "height": 200 } } })).unwrap(); + let print = s.execute("document.preflight", &json!({ "output": "print", "minPpi": 200 })).unwrap(); + let f = print["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["effectivePpi"], json!([150.0, 150.0])); +} + +#[test] +fn preflight_reports_a_frame_that_cannot_show_even_its_first_line() { + let mut s = new(); + let id = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Abc", "size": 30, "area": { "width": 100, "height": 1 } })).unwrap()["id"] + .clone(); + let r = check(&mut s); + assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}"); +} + +#[test] +fn preflight_reports_type_that_cannot_place_a_glyph_on_a_horizontal_path() { + let mut s = new(); + let path = s.execute("path.create", &json!({ "d": "M10 20 L11 20" })).unwrap()["id"].clone(); + let id = s.execute("text.createInPath", &json!({ "path": path, "mode": "onPath", "text": "Longer than the path" })).unwrap()["id"].clone(); + let r = check(&mut s); + assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}"); +} + +#[test] +fn preflight_bad_options_leave_document_and_selection_unchanged() { + let mut s = new(); + let doc = s.doc().unwrap().doc.clone(); + for p in [ + json!({ "output": "unknown" }), + json!({ "output": 1 }), + json!({ "minPpi": 0 }), + json!({ "minPpi": "300" }), + json!({ "artboards": [] }), + json!({ "artboards": [0.5] }), + json!({ "artboards": [999] }), + ] { + assert!(s.execute("document.preflight", &p).is_err(), "{p}"); + assert_eq!(*doc, *s.doc().unwrap().doc); + } +} + +#[test] +fn preflight_resource_font_finding_locates_its_instance() { + let mut s = new(); + let text = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Symbol 917" })).unwrap()["id"].clone(); + s.execute("select.set", &json!({ "ids": [text] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Label" })).unwrap(); + let r = check(&mut s); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap(); + assert!(f["ids"].as_array().unwrap().iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}"); +} + +struct Folder(std::path::PathBuf); +impl Folder { + fn new(name: &str) -> Self { + Self(vectorcraft_testkit::temp_dir(name)) + } + fn file(&self, name: &str) -> String { + self.0.join(name).to_string_lossy().into_owned() + } +} +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} +fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + let pixels = (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect(); + let image = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); + craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap() +} diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index f468bb4e00..3c2b229e1f 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() { assert_eq!(text, program(&doc)); } +/// The program written from `doc`, with the gradient and pattern definitions found by comparing +/// each in turn (`scanned`) or through their indexes. +fn program_scanned(doc: &Document, scanned: bool) -> Vec { + writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned)); + let out = export_ai_editing(doc, &opts()); + writer::SCANNED_DEFINITIONS.with(|s| s.set(false)); + out.unwrap().program +} + +/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with +/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of +/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one +/// and another gradient for the rest; one with the gradient of an object whose style isn't written +/// (an even-odd fill with a drop shadow), after that object; and two whose gradients +/// differ only in the sign of a zero offset. +fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document { + let mut doc = gradients_and_patterns(); + let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1)); + let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0)); + let more = (0..swatches) + .map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false }) + .collect(); + swatches_plus(&mut doc, more); + let mut paints = vec![]; + for i in 0..distinct { + paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None)); + } + for i in 0..reused { + paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None)); + } + for i in 0..swatches { + let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) }; + paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}")))); + } + // The reader wouldn't read an even-odd fill with the style, so the style isn't written. + let unstyled = two(Color::WHITE, Color::BLACK); + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))], + effects: vec![fx("stylize.dropShadow", serde_json::json!({}))], + contents_index: None, + }; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = FillRule::EvenOdd; + } + put(&mut doc, n); + paints.push(gradient_paint(unstyled, None, None)); + let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]); + paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]); + for (i, p) in (0u16..).zip(paints) { + let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0); + let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]); + put(&mut doc, n); + } + doc +} + +/// Gradient and pattern definitions found through their indexes are those found by comparing each +/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to +/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its +/// name free; gradients that differ only in the sign of a zero share a definition. +#[test] +fn indexed_definitions_write_the_same_program() { + let doc = many_gradients(300, 300, 7, 6); + let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true)); + let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b); + assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len()); + let text = String::from_utf8(indexed).unwrap(); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + // `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1 + // after the style + 1 for both signs of zero. + assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}"); + assert_eq!(names.iter().collect::>().len(), names.len(), "{names:?}"); + assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1); +} + +/// A gradient paint is matched with the definitions of the same gradient, not with each +/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons +/// each, where comparing each definition in turn takes hundreds of thousands. +#[test] +fn gradient_definitions_are_found_without_comparing_each() { + let doc = many_gradients(1000, 1000, 10, 0); + let comparisons = |scanned: bool| { + writer::GRADIENT_COMPARISONS.with(|c| c.set(0)); + program_scanned(&doc, scanned); + writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get) + }; + let (indexed, scanned) = (comparisons(false), comparisons(true)); + assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index"); + assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index"); +} + +/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20 +/// gradient swatches, with the definitions found by comparing each in turn and through their +/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`. +#[test] +#[ignore = "timing"] +fn gradient_definitions_timing() { + let doc = many_gradients(5000, 5000, 50, 20); + let mut times = [vec![], vec![]]; + let mut programs: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [true, false].into_iter().enumerate() { + let (start, h) = thread_time(); + let program = program_scanned(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + programs[k].get_or_insert(program); + } + } + assert_eq!(programs[0], programs[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("median of 7 runs ({how}):"); + println!("| definitions found | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, /// and reads back with each stop on its side. #[test] diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 0091d0a37c..41254840cb 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD; pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT}; #[cfg(test)] pub(super) use paints::{ - GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, + GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, + SWATCH_PLACEMENT, free_gradient_name, }; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; @@ -200,11 +201,11 @@ pub(super) struct Writer<'a> { /// pattern's definition, the pattern's space turned y up. canvas: Affine, /// The gradient definitions, in the order they are first used. - gradients: Vec, + gradients: paints::GradientDefs, /// The number the next new gradient definition's name tries first (1 is `Gradient`). next_gradient: u64, /// The pattern definitions written, each after those its art uses. - patterns: Vec, + patterns: paints::PatternDefs, /// The patterns whose definitions are being written. defining: Vec, /// Writing the palette: the definitions it adds are for its swatches only. @@ -357,9 +358,9 @@ impl<'a> Writer<'a> { grad_space: to_art, tile_grad_space: Affine::translate((-origin.0, origin.1)), canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, - gradients: vec![], + gradients: paints::GradientDefs::default(), next_gradient: 1, - patterns: vec![], + patterns: paints::PatternDefs::default(), defining: vec![], in_palette: false, canvas_origin: origin, diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 1d5651b596..5a850d7db3 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -1,7 +1,9 @@ //! Gradients and patterns: their definitions in the setup, gradient instances on paths and the //! pattern operators (see [`crate::ai_editing`] for the form). +use std::collections::HashMap; use std::fmt::Write; +use std::hash::{Hash, Hasher}; use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; @@ -46,6 +48,134 @@ pub(super) struct PatternOut { used: bool, } +#[cfg(test)] +thread_local! { + /// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing + /// the gradient or name with each definition in turn. + pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`GradientDefs::find`] has compared two gradients on this thread. + pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Are gradients `a` and `b` the same? +fn same_gradient(a: &Gradient, b: &Gradient) -> bool { + #[cfg(test)] + GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1)); + a == b +} + +/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its +/// bits, with -0 as 0); different gradients may share one. +fn gradient_key(g: &Gradient) -> u64 { + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut h = std::hash::DefaultHasher::new(); + std::mem::discriminant(&g.kind).hash(&mut h); + std::mem::discriminant(&g.method).hash(&mut h); + (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); + for s in &g.stops { + let (model, c) = match s.color { + Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), + }; + (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); + (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); + } + h.finish() +} + +/// The gradient definitions, in the order they are first used, found by name and by gradient +/// without comparing each one. +#[derive(Default)] +pub(super) struct GradientDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, + /// The places in `list` of the definitions no swatch names, in order, by their gradient's key + /// ([`gradient_key`]). + ramps: HashMap>, +} + +impl GradientDefs { + /// Is `name` a definition's name? + fn has_name(&self, name: &str) -> bool { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().any(|d| d.name == name); + } + self.names.contains_key(name) + } + + /// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else the first definition of the same gradient that no swatch names. + fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return swatch + .and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g))) + .or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g))); + } + let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g)); + swatch + .and_then(|s| self.names.get(s).copied().filter(|i| held(i, true))) + .or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false))) + } + + /// Add `d`, whose name no definition has. + fn push(&mut self, d: GradientDef) { + let i = self.list.len(); + if !d.swatch { + self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i); + } + self.names.insert(d.name.clone(), i); + self.list.push(d); + } + + /// Keep the first `len` definitions; the names of those removed are free again. + fn truncate(&mut self, len: usize) { + while self.list.len() > len { + let Some(d) = self.list.pop() else { break }; + self.names.remove(&d.name); + if !d.swatch { + // Places are added in order, so the removed definition's is the last of its key's. + let key = gradient_key(&d.gradient); + if let Some(places) = self.ramps.get_mut(&key) { + places.pop(); + if places.is_empty() { + self.ramps.remove(&key); + } + } + } + } + } +} + +/// The pattern definitions written, each after those its art uses, found by name. +#[derive(Default)] +pub(super) struct PatternDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, +} + +impl PatternDefs { + /// The place of pattern `name`'s definition. + fn find(&self, name: &str) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().position(|p| p.name == name); + } + self.names.get(name).copied() + } + + /// Add `p`, whose name no definition has. + fn push(&mut self, p: PatternOut) { + self.names.insert(p.name.clone(), self.list.len()); + self.list.push(p); + } +} + pub(in crate::ai_editing) const DIAMOND: &str = "diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps"; pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps"; @@ -118,7 +248,7 @@ impl Writer<'_> { && let stops = curve_as_stops(&g.gradient) && let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS) && writable_gradient(&gradient) - && !self.gradients.iter().any(|d| d.name == sw.name) + && !self.gradients.has_name(&sw.name) { self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false }); } @@ -131,17 +261,14 @@ impl Writer<'_> { /// swatch or a pattern). fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { let used = !self.in_palette; - let found = swatch - .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) - .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); - if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + let found = self.gradients.find(g, swatch); + if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) { d.used |= used; return d.name.clone(); } let (doc, gradients) = (self.doc, &self.gradients); - let name = free_gradient_name(&mut self.next_gradient, |name| { - gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() - }); + let name = + free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()); self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); name } @@ -149,14 +276,14 @@ impl Writer<'_> { /// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the /// art uses, and the next name's number. pub(super) fn gradient_mark(&self) -> (usize, Vec, u64) { - (self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient) + (self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient) } /// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]). pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec, u64)) { let (len, used, next) = mark; self.gradients.truncate(len); - for (d, u) in self.gradients.iter_mut().zip(used) { + for (d, u) in self.gradients.list.iter_mut().zip(used) { d.used = u; } self.next_gradient = next; @@ -476,7 +603,7 @@ impl Writer<'_> { if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol { return false; } - if self.patterns.iter().any(|p| p.name == name) { + if self.patterns.find(name).is_some() { return true; } self.doc.pattern(name).is_some_and(tile_holds_art) @@ -492,7 +619,7 @@ impl Writer<'_> { return false; } let used = !self.in_palette; - if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) { p.used |= used; return true; } @@ -582,7 +709,7 @@ impl Writer<'_> { /// uses). pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { let defs = std::mem::take(&mut self.gradients); - let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used); let _ = writeln!(s, "{} Bn", used.len()); for d in &used { self.gradient_def(s, d); @@ -595,12 +722,12 @@ impl Writer<'_> { s.push_str("%AI5_End_NonPrinting--\n"); } self.gradients = defs; - for p in self.patterns.iter().filter(|p| p.used) { + for p in self.patterns.list.iter().filter(|p| p.used) { s.push_str(&p.text); } - if self.patterns.iter().any(|p| !p.used) { + if self.patterns.list.iter().any(|p| !p.used) { s.push_str("%AI5_Begin_NonPrinting\nNp\n"); - for p in self.patterns.iter().filter(|p| !p.used) { + for p in self.patterns.list.iter().filter(|p| !p.used) { s.push_str(&p.text); } s.push_str("%AI5_End_NonPrinting--\n"); @@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool { b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn two(a: f32, b: Color) -> Gradient { + Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)]) + } + + fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef { + GradientDef { name: name.into(), gradient, swatch, used: true } + } + + /// The same gradients have the same key, a zero of either sign included. + #[test] + fn a_zero_of_either_sign_gives_the_same_key() { + assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK))); + assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK)); + assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE))); + } + + /// Definitions whose gradients share a key are told apart by their gradients, the first of the + /// same gradient found; a gradient that isn't equal to itself is found in none. + #[test] + fn definitions_that_share_a_key_are_told_apart() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Gradient", white.clone(), false)); + defs.push(def("Gradient 2", black.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + // Every definition under the black gradient's key, as if the keys of both were the same. + defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]); + assert_eq!(defs.find(&white, None), Some(0)); + let nan = two(f32::NAN, Color::BLACK); + defs.push(def("Gradient 4", nan.clone(), false)); + assert_eq!(defs.find(&nan, None), None); + } + + /// A swatch's definition is found by the swatch's name and gradient; a definition that no + /// swatch names, for the same gradient without the name or with another. + #[test] + fn a_swatch_definition_is_found_by_its_name_and_gradient() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", black.clone(), true)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), None); + assert_eq!(defs.find(&white, Some("Ramp")), None); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, Some("Ramp")), Some(2)); + assert_eq!(defs.find(&black, Some("Other")), Some(1)); + } + + /// Definitions removed leave their names free and are no longer found; those kept still are. + #[test] + fn removed_definitions_free_their_names() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", white.clone(), true)); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + defs.truncate(2); + assert!(defs.has_name("Ramp") && defs.has_name("Gradient")); + assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3")); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + assert_eq!(defs.ramps.values().map(Vec::len).sum::(), 1); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&white, None), Some(2)); + defs.truncate(0); + assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty()); + } + + /// A pattern's definition is found by its name. + #[test] + fn pattern_definitions_are_found_by_name() { + let mut defs = PatternDefs::default(); + assert_eq!(defs.find("Dots"), None); + for name in ["Dots", "Checks"] { + defs.push(PatternOut { name: name.into(), text: String::new(), used: false }); + } + assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None)); + } +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index ba38492f77..d835b457c0 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -70,6 +70,8 @@ mod tests_native; #[cfg(test)] mod tests_reads; #[cfg(test)] +mod tests_strings; +#[cfg(test)] mod tests_type1; #[cfg(test)] mod tests_type42; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c4fc09e0b0..cca8bb50ea 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -146,13 +146,21 @@ impl Interp<'_> { fn token(&mut self) -> Res { match self.pop()? { Obj::Str(s) => { - let bytes = s.to_vec(); - let mut lex = Lexer::new(&bytes); - let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) }; - let o = self.scanned(o, lex.immediate)?; - // The whitespace after the token is read with it. - let used = bytes.len() - lex.data().len(); - self.push_interval(Obj::Str(s), used, bytes.len() - used)?; + // The scanner reads the string in place. The borrow ends before `scanned`, which + // can fail or charge the budget, and before the results are pushed. + let read = { + let bytes = s.borrow(); + let mut lex = Lexer::new(&bytes); + // The whitespace after the token is read with it. + lex.next()?.map(|o| { + let immediate = lex.immediate; + let rest = lex.data().len(); + (o, immediate, bytes.len() - rest, rest) + }) + }; + let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) }; + let o = self.scanned(o, immediate)?; + self.push_interval(Obj::Str(s), used, rest)?; self.push(o)?; } Obj::File { stream: f, .. } => { diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 43346988ff..8d883a0bff 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -753,21 +753,25 @@ impl<'a> Interp<'a> { } fn search_string(&mut self, op: Op) -> Res { - let seek = self.pop_str()?.to_vec(); + let seek = self.pop_str()?; let s = self.pop_str()?; - let text = s.to_vec(); - self.spend((text.len() / 64) as u64)?; - let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + // Both strings are read in place, and the borrows end before the results are pushed. + let (len, n, at) = { + let (text, seek) = (s.borrow(), seek.borrow()); + self.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + (text.len(), seek.len(), at) + }; match at { Some(i) => { let o = Obj::Str(s); if op == Op::Search { - self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; - self.push_interval(o.clone(), i, seek.len())?; + self.push_interval(o.clone(), i + n, len - i - n)?; + self.push_interval(o.clone(), i, n)?; self.push_interval(o, 0, i)?; } else { - self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; - self.push_interval(o, 0, seek.len())?; + self.push_interval(o.clone(), n, len - n)?; + self.push_interval(o, 0, n)?; } self.push(Obj::Bool(true))?; } diff --git a/crates/eps/src/import/obj.rs b/crates/eps/src/import/obj.rs index 2b3ae92c73..1fcd41dd85 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -49,6 +49,8 @@ thread_local! { /// Tests: the arrays of the list last released on this thread that were still alive after it /// (the ones the interpreter itself still held). pub(crate) static ARRAYS_LEFT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many values [`Shared::to_vec`] has copied on this thread. + pub(crate) static VALUES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { @@ -340,7 +342,10 @@ impl Shared { } pub fn to_vec(&self) -> Vec { - self.borrow().to_vec() + let v = self.borrow().to_vec(); + #[cfg(test)] + VALUES_COPIED.with(|n| n.set(n.get() + v.len())); + v } /// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end. diff --git a/crates/eps/src/import/tests_strings.rs b/crates/eps/src/import/tests_strings.rs new file mode 100644 index 0000000000..2a07dafd7c --- /dev/null +++ b/crates/eps/src/import/tests_strings.rs @@ -0,0 +1,306 @@ +//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read +//! their strings in place. The tests run them next to reference readers that copy the strings +//! first, on the same operands in the same interpreter state: the operand stack, the error and the +//! operations spent must agree. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::time::{Duration, Instant}; + +use vectorcraft_doc::Document; +use vectorcraft_geom::{Affine, Rect}; + +use super::graphics::{GState, Out}; +use super::interp::Interp; +use super::lex::Lexer; +use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED}; + +/// An interpreter that has run `src`, with the operands it left. +fn after(src: &[u8]) -> Interp<'_> { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src)); + it +} + +/// The reference `token`: the string copied before it is scanned. +fn token_by_copy(it: &mut Interp) -> Res { + match it.pop()? { + Obj::Str(s) => { + let bytes = s.to_vec(); + let mut lex = Lexer::new(&bytes); + let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, lex.immediate)?; + let used = bytes.len() - lex.data().len(); + it.push_interval(Obj::Str(s), used, bytes.len() - used)?; + it.push(o)?; + } + Obj::File { stream: f, .. } => { + let (o, immediate) = it.next_in(&f)?; + let Some(o) = o else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, immediate)?; + it.push(o)?; + } + _ => return Err(PsError::Ps("typecheck", "token".into())), + } + it.push(Obj::Bool(true)) +} + +/// The reference `search` and `anchorsearch`: both strings copied before they are compared. +fn search_by_copy(it: &mut Interp, op: Op) -> Res { + let seek = it.pop_str()?.to_vec(); + let s = it.pop_str()?; + let text = s.to_vec(); + it.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + match at { + Some(i) => { + let o = Obj::Str(s); + if op == Op::Search { + it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; + it.push_interval(o.clone(), i, seek.len())?; + it.push_interval(o, 0, i)?; + } else { + it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; + it.push_interval(o, 0, seek.len())?; + } + it.push(Obj::Bool(true))?; + } + None => { + it.push(Obj::Str(s))?; + it.push(Obj::Bool(false))?; + } + } + Ok(()) +} + +fn by_copy(it: &mut Interp, op: Op) -> Res { + if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) } +} + +/// The error's name, or the limit reached. +fn outcome(r: Res) -> Result<(), String> { + r.map_err(|e| match e { + PsError::Ps(name, _) => name.to_string(), + e => format!("{e:?}"), + }) +} + +/// Everything the operator left: the operand stack with each string's storage, offset and length, +/// and the operations spent. +fn state(it: &Interp) -> (String, u64) { + (format!("{:?}", it.stack), it.ops_left()) +} + +/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds +/// each call the string the last one left), and check that the two agree after every call. +fn agree(src: &str, op: Op, steps: usize) { + let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes())); + // `search` and `anchorsearch` look for the same string on each call. + let seeks = [new.stack.last().cloned(), old.stack.last().cloned()]; + for step in 0..steps { + let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op))); + assert_eq!(a, b, "{src} {op:?}, call {step}"); + assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}"); + // Keep walking while the operator answered true, with the string it left. + let more = matches!(new.stack.last(), Some(Obj::Bool(true))); + if a.is_err() || !more { + break; + } + for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) { + it.stack.pop(); + // `token` leaves the rest under the object; `search` leaves it under match and pre + // (and `anchorsearch` under the match). + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.truncate(keep); + // The string to look for again, or the file `token` reads on from. + if op != Op::Token || matches!(seek, Some(Obj::File { .. })) { + it.stack.extend(seek.clone()); + } + } + } + new.release(); + old.release(); +} + +#[test] +fn token_and_search_agree_with_copying_readers() { + let tokens = [ + "()", + "( )", + "(\r\n\t )", + "(12)", + "(12 34)", + "(12 34)", + "(12\r\n34)", + "(/x {a b} (s) <41> 1.5 x)", + "(1 {)", + "( [ 1 ] )", + "/x 7 def (//x {//x} y)", + "(xx12 34 56) 2 7 getinterval", + "(%comment only)", + "5", + "(12 /x {a}) /ReusableStreamDecode filter", + "currentfile", + ]; + for src in tokens { + agree(src, Op::Token, 16); + } + let searches = [ + "(abcabc) (bc)", + "(abc) (x)", + "(abc) ()", + "() ()", + "() (a)", + "(ab) (abc)", + "(a\nb\nc\n) (\n)", + "/s (aa) def s s", + "(xxab cd ef) 2 8 getinterval ( )", + "(abc) 5", + "5 (abc)", + ]; + for src in searches { + agree(src, Op::Search, 8); + agree(src, Op::AnchorSearch, 8); + } + // Over the operation budget: the same error, with the same operands popped. + let big = "/h 65536 string def h (\\001)"; + let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes())); + for it in [&mut new, &mut old] { + let left = it.ops_left(); + assert_eq!(it.spend(left.saturating_sub(10)), Ok(())); + } + let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search))); + assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}"); + assert_eq!((a, state(&new)), (b, state(&old))); + new.release(); + old.release(); +} + +/// The results share the string's storage: a write to the string after `token` or `search` shows +/// in what they left. +#[test] +fn token_and_search_results_see_later_writes() { + let check = super::tests::check; + check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq"); + check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and"); + check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq"); + check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq"); +} + +/// `token` on a string, `search` and `anchorsearch` copy neither string. +#[test] +fn token_and_search_copy_no_string() { + for (src, op) in [ + ("(12 34 56 78)", Op::Token), + ("(abc def ghi) ( )", Op::Search), + ("(abc def ghi) (xyz)", Op::Search), + ("(abc def ghi) (abc)", Op::AnchorSearch), + ("(abc def ghi) (def)", Op::AnchorSearch), + ] { + let mut it = after(src.as_bytes()); + VALUES_COPIED.with(|n| n.set(0)); + assert_eq!(it.op(op), Ok(()), "{src} {op:?}"); + assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}"); + it.release(); + } +} + +/// The median of `runs`. +fn median(runs: &[Duration]) -> Duration { + let mut sorted = runs.to_vec(); + sorted.sort(); + sorted.get(sorted.len() / 2).copied().unwrap_or_default() +} + +/// What a walk records of each result: a string's length and first bytes, any other object whole. +fn mark(o: &Obj, h: &mut impl Hasher) { + match o { + Obj::Str(s) => { + s.len().hash(h); + s.borrow().iter().take(16).for_each(|b| b.hash(h)); + } + o => format!("{o:?}").hash(h), + } +} + +/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy +/// or in place: how long it took, the calls made, and a hash of every result and of the operations +/// spent. The interpreter is made before the clock starts. +fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) { + let mut it = after(b""); + it.stack.push(Obj::Str(Shared::new(data.to_vec()))); + let mut calls = 0; + let mut h = DefaultHasher::new(); + let start = Instant::now(); + loop { + if let Some(seek) = seek { + it.stack.push(Obj::Str(Shared::new(seek.to_vec()))); + } + let r = if copy { by_copy(&mut it, op) } else { it.op(op) }; + assert_eq!(r, Ok(())); + calls += 1; + if !matches!(it.stack.pop(), Some(Obj::Bool(true))) { + break; + } + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.stack.truncate(keep); + } + let took = start.elapsed(); + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.ops_left().hash(&mut h); + it.release(); + (took, calls, h.finish()) +} + +/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the +/// same, and print every run and the medians. +fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) { + let (mut old, mut new) = (vec![], vec![]); + let mut calls = 0; + for run in 0..7 { + let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] }; + let mut got = vec![]; + for copy in order { + let (took, n, last) = walk(data, op, seek, copy); + if copy { + old.push(took) + } else { + new.push(took) + } + calls = n; + got.push((n, last)); + } + assert!(got.first() == got.get(1), "{what}: the readers differ"); + } + let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0); + println!("{what}: {} bytes, {calls} calls", data.len()); + println!(" by copy, ms: {}", old.iter().map(ms).collect::>().join(" ")); + println!(" in place, ms: {}", new.iter().map(ms).collect::>().join(" ")); + let (o, w) = (median(&old), median(&new)); + println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9)); +} + +/// Times `token` and `search` walking a string by what each call leaves, against the copying +/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names +/// for `token` and of 128-byte lines for `search`. Run it in release: +/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn string_walks_timed() { + for kib in [4, 64, 512] { + let size = kib * 1024; + let mut words = Vec::with_capacity(size + 16); + let mut i = 0u32; + while words.len() < size { + let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") }; + words.extend_from_slice(w.as_bytes()); + i += 1; + } + compare(&format!("token, {kib} KiB"), &words, Op::Token, None); + let lines: Vec = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect(); + compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n")); + } +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 56b2f95944..2c16587227 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1636,6 +1636,64 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn transform_refused_by_a_later_operation_changes_nothing() { + let mut s = server(); + let count = |s: &mut Server| -> u64 { + let r = call(s, 90, "inspect_document", json!({})); + serde_json::from_str::(&text_of(&r)).unwrap()["objects"].as_u64().unwrap() + }; + let base = count(&mut s); + let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50}))); + let before = doc_json(&mut s); + for (id, args, says) in [ + (2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"), + (3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"), + (4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"), + (5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"), + (6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"), + ] { + let t = call(&mut s, id, "transform", args.clone()); + assert_eq!(t["isError"], true, "{args}: {t}"); + assert!(text_of(&t).contains(says), "{args}: {t}"); + assert_eq!(doc_json(&mut s), before, "{args}"); + } + // No undo step was recorded: one undo removes the rectangle. + assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false); + assert_eq!(count(&mut s), base, "one undo removes the rectangle"); +} + +#[test] +fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + let cases = [ + ("object.reflect", json!({"dx": 10, "reflect": 42, "copy": true})), + ("object.reflect", json!({"dx": 10, "reflect": true})), + ("copy", json!({"dx": 10, "copy": "yes"})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": "center", "copy": true})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": [5]})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": [5, "a"]})), + ]; + for (index, (says, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args.clone()); + assert_eq!(rejected["isError"], true, "{args}: {rejected}"); + assert!(text_of(&rejected).contains(says), "{args}: {rejected}"); + // The document, the selection and the undo history are as they were. + assert_eq!(inspect(&mut s, request_id + 1), before, "{args}"); + } + // A null `reflect`, `copy` or `origin` is left out. + let applied = call(&mut s, 20, "transform", json!({"ids": [second], "dx": 10, "reflect": null, "copy": null, "origin": null})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move"])); +} + #[test] fn add_text_rejects_invalid_path_effects_before_editing() { let mut s = server(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 1b86095c6e..642f65fbfe 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection center; `copy` transforms a copy. A scale, reflect or shear its command refuses, or an argument of the wrong type, returns that error before any step runs, and nothing changes.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 8841c050ee..cd7a0fc20b 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -302,9 +302,42 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { + // Each operation is its own command: check the params the later ones refuse before the first + // runs, so a refused request changes nothing. The `transform` arm of `dispatch` has already + // refused a `dx`, `dy`, `rotate`, `scale`, `scaleX`, `scaleY` or `shear` that is not a number. + fn bad(cmd: &'static str) -> impl Fn(String) -> String { + move |e| format!("invalid parameters for `{cmd}`: {e}") + } + let s = a.get("scale").and_then(Value::as_f64); + let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); + if sx.is_some() || sy.is_some() { + vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; + } + // A null `reflect`, `copy` or `origin` is left out. + let reflect = match a.get("reflect") { + None | Some(Value::Null) => None, + Some(Value::String(axis)) => Some(axis.as_str()), + Some(v) => return Err(format!("invalid parameters for `object.reflect`: axis must be \"vertical\" or \"horizontal\", not `{v}`")), + }; + if let Some(axis) = reflect { + vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; + } + let shear = a.get("shear").and_then(Value::as_f64); + if let Some(sh) = shear { + vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; + } + let copy = match a.get("copy") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| format!("`copy` must be true or false, not {v}"))?, + }; + if let Some(o) = a.get("origin").filter(|o| !o.is_null()) + && !o.as_array().is_some_and(|xy| xy.len() == 2 && xy.iter().all(Value::is_number)) + { + return Err(format!("`origin` must be [x, y], not {o}")); + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). - let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); + let copy = std::cell::Cell::new(copy); let with = |mut p: Value| { if let Some(o) = a.get("origin") { p["origin"] = o.clone(); @@ -322,17 +355,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result exec(b, "object.rotate", with(json!({"angle": r})))?; done.push("rotate"); } - let s = a.get("scale").and_then(Value::as_f64); - let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); if sx.is_some() || sy.is_some() { exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?; done.push("scale"); } - if let Some(axis) = a.get("reflect").and_then(Value::as_str) { + if let Some(axis) = reflect { exec(b, "object.reflect", with(json!({"axis": axis})))?; done.push("reflect"); } - if let Some(sh) = a.get("shear").and_then(Value::as_f64) { + if let Some(sh) = shear { exec(b, "object.shear", with(json!({"angle": sh})))?; done.push("shear"); } diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b9b53059b4..7ca1aa679e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -688,7 +688,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -1026,7 +1026,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index a42e628cad..655e84e311 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -8,6 +8,9 @@ //! Both are found as roots over the normal's angle: sampled, then refined by bisection, with //! sampled minima refined too so that a double root (outlines that touch) or two roots between //! neighboring samples are kept. +//! +//! One of the two may be a point instead ([`Outline::point`]): its support value is `p · n`, and +//! the tangents are the lines through it that touch the other outline. use std::f64::consts::TAU; @@ -60,7 +63,7 @@ pub enum OutlineError { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Coincide; -/// A convex closed outline that [`common_tangents`] takes. +/// A convex closed outline, or a point, that [`common_tangents`] takes. #[derive(Clone, Debug)] pub enum Outline { /// The unit circle under an affine map: the center is the map's translation, `m` its linear @@ -70,9 +73,19 @@ pub enum Outline { /// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then /// comes later in the list as the angle of `n` grows. Convex { segments: Vec, center: Point, size: f64, ccw: bool }, + /// A single point. + Point { at: Point }, } impl Outline { + /// The point `at`, whose tangents are the lines through it. + pub fn point(at: Point) -> Result { + if !at.x.is_finite() || !at.y.is_finite() { + return Err(OutlineError::Empty); + } + Ok(Outline::Point { at }) + } + /// The ellipse that `unit` maps the unit circle onto. pub fn ellipse(unit: Affine) -> Result { let [a, b, c, d, e, f] = unit.as_coeffs(); @@ -183,6 +196,7 @@ impl Outline { size: *size, ccw: *ccw, }, + Outline::Point { at } => Outline::Point { at: *at + d }, } } @@ -203,7 +217,7 @@ impl Outline { /// The support value at `n` and the segment it is reached on, from every segment. fn support_scan(&self, n: Vec2) -> (f64, usize) { match self { - Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0), Outline::Convex { segments, .. } => { let mut best = (f64::MIN, 0); for (i, s) in segments.iter().enumerate() { @@ -222,7 +236,7 @@ impl Outline { /// where the support value was reached at a normal angle a little less than `n`'s. fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) { match self { - Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0), Outline::Convex { segments, ccw, .. } => { let len = segments.len(); if len == 0 { @@ -251,14 +265,20 @@ impl Outline { } } - /// The center: an ellipse's, or a path's center of area. + /// The center: an ellipse's, a path's center of area, or the point itself. pub fn center(&self) -> Point { match self { Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center, + Outline::Point { at } => *at, } } - /// The diagonal of the bounds (an ellipse's: of the box its axes span). + /// Whether this is a point. + pub fn is_point(&self) -> bool { + matches!(self, Outline::Point { .. }) + } + + /// The diagonal of the bounds (an ellipse's: of the box its axes span; a point's: 0). pub fn size(&self) -> f64 { match self { Outline::Ellipse { m, .. } => { @@ -266,6 +286,7 @@ impl Outline { 2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt() } Outline::Convex { size, .. } => *size, + Outline::Point { .. } => 0.0, } } @@ -280,6 +301,7 @@ impl Outline { } best } + Outline::Point { at } => at.to_vec2().dot(n), } } @@ -320,6 +342,7 @@ impl Outline { let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() } + Outline::Point { at } => vec![*at], } } } @@ -406,7 +429,14 @@ fn dir(angle: f64) -> Vec2 { /// the angle of its normal. Separate outlines have two of each; overlapping ones only external /// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the /// other none; outlines that touch share one tangent where they touch. +/// +/// When one of them is a point, its external and internal tangents are the same lines, and they +/// come back as external ones: two when the point lies outside the other outline, one when it lies +/// on it, none inside. Two points have none. pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincide> { + if a.is_point() && b.is_point() { + return Ok(vec![]); + } // Worked out about the point between the two centers. let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0; let (a, b) = (&a.shifted(-origin), &b.shifted(-origin)); @@ -434,7 +464,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincid let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0)); let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; - let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let internal = if a.is_point() || b.is_point() { + vec![] + } else { + roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)? + }; let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb }); let mut out = Vec::with_capacity(external.len() + internal.len()); for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { @@ -506,8 +540,13 @@ fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: boo // A double root's angle is found less exactly than a simple one's, so touching points may // stand a little apart. let (from, to) = if double && hi - lo <= 1e-6 * size { - // Touching at one point: the narrower outline's width along the line, centered there. - let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min); + // Touching at one point: the narrower outline's width along the line, centered there. A + // point on the other outline takes that outline's width. + let width = [a, b] + .into_iter() + .filter(|o| !o.o.is_point()) + .map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0) + .fold(f64::MAX, f64::min); let mid = (lo + hi) / 2.0; (mid - width / 2.0, mid + width / 2.0) } else if mean(&on_a) <= mean(&on_b) { @@ -975,6 +1014,127 @@ mod tests { assert!((best - 0.25).abs() < 1e-12, "{best}"); } + #[test] + fn a_point_outside_a_turned_ellipse_has_two_tangents_through_it() { + let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0); + let (oval, p) = (Outline::ellipse(m).unwrap(), Point::new(-60.0, 120.0)); + let samples = sample_ellipse(m, 5_000); + for point_first in [true, false] { + let point = Outline::point(p).unwrap(); + let all = if point_first { common_tangents(&point, &oval) } else { common_tangents(&oval, &point) }.unwrap(); + assert_eq!(all.len(), 2, "{all:?}"); + for t in &all { + assert_eq!(t.kind, TangentKind::External); + // Each runs from the first outline given to the second: from the point when it + // comes first. + let (at_point, on_oval) = if point_first { (t.from, t.to) } else { (t.to, t.from) }; + assert!((at_point - p).hypot() < 1e-9, "{t:?}"); + // Taken back to the unit circle, the far end lies on it and the line runs square to + // its radius there. + let inv = m.inverse(); + let (q, d) = ((inv * on_oval).to_vec2(), (inv * on_oval) - (inv * at_point)); + assert!((q.hypot() - 1.0).abs() < 1e-9, "{q:?}"); + assert!((q.dot(d) / d.hypot()).abs() < 1e-7, "{q:?} {d:?}"); + // The whole ellipse lies on one side of the line. + let dir = on_oval - at_point; + let n = Vec2::new(-dir.y, dir.x) / dir.hypot(); + let side: Vec = samples.iter().map(|s| (*s - at_point).dot(n)).collect(); + let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!(lo > -1e-6 || hi < 1e-6, "crosses: {lo} .. {hi}"); + } + } + } + + #[test] + fn a_point_on_inside_and_beside_a_path() { + // On a circle: the one tangent there, centered on the point and as long as the circle is + // wide. + let on = common_tangents(&Outline::point(Point::new(10.0, 0.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap(); + assert_eq!(on.len(), 1, "{on:?}"); + assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{on:?}"); + // Inside, and two points: none. + assert!(common_tangents(&Outline::point(Point::new(3.0, 4.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap().is_empty()); + let two = (Outline::point(Point::new(0.0, 0.0)).unwrap(), Outline::point(Point::new(5.0, 0.0)).unwrap()); + assert!(common_tangents(&two.0, &two.1).unwrap().is_empty()); + // Beside a square, in line with its bottom side: that tangent covers the whole side, and + // the other one touches the corner at (10, 10). + let square = SubPath::polyline(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(Point::from), true); + let sq = Outline::convex(&square).unwrap(); + let p = Point::new(20.0, 0.0); + let all = common_tangents(&Outline::point(p).unwrap(), &sq).unwrap(); + assert_eq!(all.len(), 2, "{all:?}"); + assert!(all.iter().any(|t| ends_at(t, p, Point::new(0.0, 0.0))), "{all:?}"); + assert!(all.iter().any(|t| ends_at(t, p, Point::new(10.0, 10.0))), "{all:?}"); + assert!(all.iter().all(|t| (t.from - p).hypot() < 1e-9), "from the point: {all:?}"); + // On a straight side, off its middle: the one tangent is that side, covered whole. + let side = common_tangents(&Outline::point(Point::new(2.0, 0.0)).unwrap(), &sq).unwrap(); + assert_eq!(side.len(), 1, "{side:?}"); + assert!(ends_at(&side[0], Point::new(0.0, 0.0), Point::new(10.0, 0.0)), "{side:?}"); + // At a corner of the square: one line through the corner, at the middle of the directions + // that touch there, as long as the square is wide along it. + let corner = common_tangents(&Outline::point(Point::new(10.0, 10.0)).unwrap(), &sq).unwrap(); + assert_eq!(corner.len(), 1, "{corner:?}"); + // The diagonal is 10√2 long, so each end lies 5√2 from the corner, along (1, -1). + assert!(ends_within(&corner[0], Point::new(15.0, 5.0), Point::new(5.0, 15.0), 1e-5), "{corner:?}"); + // A point that is not finite is refused. + assert_eq!(Outline::point(Point::new(f64::NAN, 0.0)).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::point(Point::new(0.0, f64::INFINITY)).err(), Some(OutlineError::Empty)); + } + + #[test] + fn a_point_placed_on_a_turned_outline_has_one_tangent() { + // A point worked out on the outline lies a rounding error inside or outside it, and still + // gets the one line there, as long as the outline is wide along it. + let one = |p: Point, o: &Outline, samples: &[Point]| { + let all = common_tangents(&Outline::point(p).unwrap(), o).unwrap(); + assert_eq!(all.len(), 1, "{p:?}: {all:?}"); + // The line runs through the point. + let (a, d) = (all[0].from, all[0].to - all[0].from); + assert!(d.hypot() > 1.0 && ((p - a).cross(d) / d.hypot()).abs() < 1e-6, "{p:?}: {all:?}"); + // Its length is the outline's width along it, measured on dense samples. + let u = d / d.hypot(); + let (lo, hi) = samples.iter().map(|s| s.to_vec2().dot(u)).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v))); + assert!((d.hypot() - (hi - lo)).abs() < 1e-3, "{p:?}: {} against {}", d.hypot(), hi - lo); + }; + let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0); + let (oval, oval_samples) = (Outline::ellipse(m).unwrap(), sample_ellipse(m, 20_000)); + for k in 0..37 { + let a = 0.17 + k as f64 * TAU / 37.0; + one(m * Point::new(a.cos(), a.sin()), &oval, &oval_samples); + } + // A closed Bézier circle, turned and moved: on each anchor and partway along each segment. + let turned = shapes::ellipse(Rect::new(-60.0, -60.0, 60.0, 60.0)).transformed(Affine::translate((37.3, -12.9)) * Affine::rotate(0.7)); + let sp = turned.subpaths[0].clone(); + let (path, path_samples) = (Outline::convex(&sp).unwrap(), sample_path(&sp, 5_000)); + for an in sp.anchors.iter() { + one(an.p, &path, &path_samples); + } + for k in 0..sp.segment_count() { + for t in [0.21, 0.5, 0.83] { + one(sp.segment(k).eval(t), &path, &path_samples); + } + } + } + + #[test] + fn a_point_within_the_touching_tolerance_counts_as_on_the_outline() { + // The tolerance is a billionth of the larger of the circle's size and the point's distance + // from its center: closer than that, inside or outside, the point gets the one line there. + let round = circle(0.0, 0.0, 10.0); + let tol = 1e-9 * round.size().max(10.0); + let at = |dx: f64| common_tangents(&Outline::point(Point::new(10.0 + dx, 0.0)).unwrap(), &round).unwrap(); + for dx in [-0.5 * tol, 0.5 * tol] { + let on = at(dx); + assert_eq!(on.len(), 1, "{dx}: {on:?}"); + assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{dx}: {on:?}"); + } + // Farther than that, a point inside gets none and a point outside gets two. + assert!(at(-100.0 * tol).is_empty()); + assert_eq!(at(100.0 * tol).len(), 2); + assert!(at(-1e-6).is_empty()); + assert_eq!(at(1e-6).len(), 2); + } + #[test] fn open_concave_empty_and_identical_outlines_are_refused() { let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index a8dd48628c..2fccfb393c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash "; /// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it /// keeps every offset. const PLACEHOLDER: &str = "0000000000000000"; -/// Deepest name tree searched for the editing file. -const MAX_DEPTH: usize = 16; +/// The most name tree nodes searched for the editing file. +const MAX_NODES: usize = 1 << 16; /// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { editing_in(&crate::pages::open(bytes, password).ok()?) } +/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]). +struct Search<'a> { + /// The editing file's file specification, if one was found. + spec: Option>, + /// A name tree key searched names the editing file (set also when its file specification + /// can't be read). + keyed: bool, + /// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched. + cut: bool, +} + +/// The search of a parsed PDF's attachments for the editing file. +fn editing_file_spec(pdf: &Pdf) -> Search<'_> { + let xref = pdf.xref(); + let Some(tree) = xref + .get::>(xref.root_id()) + .and_then(|catalog| catalog.get::>(b"Names")) + .and_then(|names| names.get::>(b"EmbeddedFiles")) + else { + return Search { spec: None, keyed: false, cut: false }; + }; + let (mut keyed, mut cut) = (false, false); + let spec = editing_spec(tree, &mut keyed, &mut cut, xref); + Search { spec, keyed, cut } +} + +/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't +/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be +/// resolved)? Also true when the name tree is too large to search to its end. +pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { + let search = editing_file_spec(pdf); + search.spec.is_some() || search.keyed || search.cut +} + +/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`] +/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it +/// reads. +pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool { + editing_file_spec(pdf).cut +} + /// [`editing`] of a parsed PDF. pub(crate) fn editing_in(pdf: &Pdf) -> Option { - let xref = pdf.xref(); - let catalog = xref.get::>(xref.root_id())?; - let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; + let spec = editing_file_spec(pdf).spec?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect -/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { +/// The first file specification of the editing file in the name tree `tree`, searched in order at +/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the +/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is +/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is +/// set when a key searched names the editing file, and `cut` when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option> { + let mut seen = HashSet::::new(); + let mut nodes = vec![tree]; + let mut found = None; + // Nodes still to be searched, counting the ones waiting in `nodes`. + let mut left = MAX_NODES - 1; + while let Some(node) = nodes.pop() { + // Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut. + if found.is_none() { + found = node_spec(&node, keyed, xref); + } + let Some(kids) = node.get::>(b"Kids") else { continue }; + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + let mut kids: Vec> = items(&kids) + .filter_map(|raw| match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(kid)) => Some(kid), + _ => None, + }) + .take(left.saturating_add(1)) + .collect(); + if kids.len() > left { + *cut = true; + kids.truncate(left); + } + left -= kids.len(); + nodes.extend(kids.into_iter().rev()); + } + found +} + +/// The file specification of the editing file among the name tree node `node`'s own `Names`. +/// `keyed` is set when a key names the editing file. +fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { + // The keys read as written, so a value that can't be resolved doesn't shift the pairs. + let mut raw = items(&names); + while let (Some(key), Some(_)) = (raw.next(), raw.next()) { + let key = match key { + MaybeRef::NotRef(Object::String(key)) => Some(key), + MaybeRef::Ref(r) => xref.get::>(r.into()), + MaybeRef::NotRef(_) => None, + }; + if key.is_some_and(|key| is_editing_name(&key)) { + *keyed = true; + } + } let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { if let Object::Dict(spec) = spec @@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet= MAX_DEPTH { - return None; - } - let kids = node.get::>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The - // reference is checked before the kid is read, so a shared kid is read once. - items(&kids).find_map(|raw| { - let kid = match raw { - MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, - MaybeRef::NotRef(Object::Dict(kid)) => kid, - _ => return None, - }; - editing_spec(&kid, depth + 1, seen, xref) - }) + None } /// A file specification naming the editing file (current or legacy name), in any text string /// encoding. fn is_editing_file(spec: &Dict<'_>) -> bool { - [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| { - let name = text_string(name.as_bytes()); - name == EDITING_FILE || name == LEGACY_EDITING_FILE - }) + [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| is_editing_name(&name)) +} + +/// A text string that is the editing file's name (current or legacy), in any encoding. +fn is_editing_name(name: &PdfString<'_>) -> bool { + let name = text_string(name.as_bytes()); + name == EDITING_FILE || name == LEGACY_EDITING_FILE } /// The most decoded page content [`page_hash`] reads in all (bytes). diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index b7c967989e..bd241421c7 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -64,8 +64,8 @@ pub(crate) struct Sheet<'a> { impl Writer { /// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata - /// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in - /// CMYK (unless the colours are converted to RGB). + /// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency + /// blends in CMYK (unless the colours are converted to RGB). pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option, cmyk: bool) -> Result { let out = ColorOut::new(doc, set)?; let mut warnings = out.profile_notes.clone(); @@ -111,7 +111,11 @@ impl Writer { created: created.map(date_time), modified: None, }; - let pdf = write::Writer::new(settings, metadata); + // The document language (Document Setup) as the catalog's `Lang` and the XMP packet's + // `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes + // none rather than a guess. + let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string); + let pdf = write::Writer::new_with_language(settings, metadata, language); Ok(Self { pdf, cmyk: out.blends_cmyk(cmyk), diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 470432aa8f..ec593baf24 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -261,6 +261,18 @@ impl Opened { crate::editing::editing_in(&self.pdf) } + /// Does the PDF list the editing file among its attachments, also when + /// [`editing`](Self::editing) can't read it? + pub fn has_editing_file(&self) -> bool { + crate::editing::has_editing_file_in(&self.pdf) + } + + /// Is the PDF's attachment name tree too large to search to its end? It may then list an + /// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads. + pub fn editing_search_cut(&self) -> bool { + crate::editing::editing_search_cut_in(&self.pdf) + } + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. pub fn illustrator_data(&self) -> Option> { private_data(&self.pdf) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 91c037ad84..e2abe87637 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() { assert!(s.contains("/ViewerPreferences<>"), "viewers should show the document title (#3646)"); } +/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any. +fn catalog_lang(pdf: &[u8]) -> Option { + let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table"); + let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog"); + let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary"); + let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned(); + let at = catalog.find("/Lang")? + "/Lang".len(); + let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string"); + Some(rest[..rest.find(')').expect("a closed string")].to_string()) +} + +/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in +/// exported and printed PDFs, and the XMP packet says it too (#3644). +#[test] +fn the_catalog_gives_the_document_language() { + let mut d = doc(100.0, 100.0); + for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] { + if let Some(language) = language { + d.setup.language = language.into(); + } + for opts in [PdfOptions::uncompressed(), PdfOptions::default()] { + let bytes = export(&d, &opts).unwrap(); + assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}"); + } + // Print to PDF writes its file with the same writer. + let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap(); + assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed"); + let s = uncompressed(&d); + assert!(s.contains(&format!("{tag}")), "{language:?}: {s}"); + } + // A language without a tag (from a file) writes none rather than a guess. + d.setup.language = "Klingon".into(); + assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None); +} + /// A function or colour space built on itself is refused before the interpreter builds it (by /// recursion, with no cap: a stack overflow), and those of real files are read. #[test] diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index c4f2900709..b58c953c2f 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -237,3 +237,104 @@ fn a_file_name_written_as_utf16_is_found() { assert_eq!(e.data, b"hello", "/{key}"); } } + +#[test] +fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { + // No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object. + for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{ef:?}"); + assert!(opened.has_editing_file(), "{ef:?}"); + } + // A name tree key naming it, with a file specification that names no object or isn't one. + for spec in ["9 0 R", "(not a file specification)"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{spec}"); + assert!(opened.has_editing_file(), "{spec}"); + } + // The key written as an indirect string. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + "<< /Names [5 0 R 9 0 R] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + format!("({EDITING_FILE})"), + ]; + assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file()); + // A PDF without the editing file, and one with it. + assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file()); + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && opened.has_editing_file()); +} + +#[test] +fn an_editing_file_deep_in_the_name_tree_is_found() { + // Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing + // file sits in the leaf (object 204), with its data or naming data that can't be resolved. + for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] { + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(), + "<< /Kids [4 0 R] >>".to_string(), + ]; + for node in 4..=203 { + objects.push(format!("<< /Kids [{} 0 R] >>", node + 1)); + } + objects.push("<< /Names [(a) 205 0 R] >>".to_string()); + objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>")); + objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string()); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string()); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert!(opened.has_editing_file(), "{ef}"); + let data = opened.editing().map(|e| e.data); + assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}"); + } + // A name tree with more nodes than are searched may list it. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // One that lists a readable editing file before the nodes left unsearched and another after + // them: the first is read, and the search reads as cut short. + let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>"); + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)), + leaf(6), + leaf(7), + "<< /Length 5 >>\nstream\nfirst\nendstream".to_string(), + "<< /Length 6 >>\nstream\nsecond\nendstream".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // The same, with the nodes past the limit in a subtree after the one holding the first. + let mut objects = objects; + objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000)); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // A tree searched to its end. + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && !opened.editing_search_cut()); +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b304e1721e..019dd0d858 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -53,7 +53,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; -pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms}; +pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5a2db2ff0d..0cb6197e97 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000; /// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; +/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input +/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large +/// ([`Plugin::large_limits`]): 5 times the default. +pub const LARGE_FUEL: u64 = 250_000_000; + /// The limit a run reports when its input and parameters together are past half its memory. pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)"; @@ -215,6 +220,12 @@ impl Plugin { pub fn limits(&self) -> &Limits { &self.limits } + /// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides + /// those for each byte of input, and every other limit, the time budget included, as it is. A + /// heavy filter keeps its larger budget. + pub fn large_limits(&self) -> Limits { + Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() } + } /// Module size in bytes. pub fn size(&self) -> usize { self.size diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index abc2cd05eb..26dec0a7d2 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -7,7 +7,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() { assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); } +/// The Large instruction budget gives a light filter 5 times the instructions besides those for +/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the +/// same time budget. A heavy filter keeps its larger budget, and every other limit stays. +#[test] +fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() { + let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap(); + assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); + let large = light.large_limits(); + assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() }); + assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base); + assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes()); + let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; + let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap(); + assert_eq!(heavy.large_limits(), *heavy.limits()); + assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); +} + #[test] fn an_exporter_returns_its_file_with_an_export_s_budget() { use vectorcraft_plugins::export::{self, Target}; diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index dc459d4331..fff66aa142 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -203,6 +203,21 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal finish(px, &colors, width, height, &palette, o, o.dither) } +/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures +/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a +/// pixel that becomes transparent, and for every pixel when `palette` is empty. +pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { + let px = rgba.as_chunks::<4>().0; + let colors = opaque_colors(px, o, false); + let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); + let index = PaletteIndex::new(&pal, o.reduction.weights()); + colors + .iter() + .zip(px) + .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) + .collect() +} + /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { let matte = o.matte.unwrap_or([255; 3]); diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 10063a5da4..7eb480a414 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -80,14 +80,19 @@ fn lossy_makes_runs_and_smaller_gifs() { let px = image(96, 64, |x, y| [(x * 2 + y) as u8, (y * 3) as u8, ((x * y) % 255) as u8]); let ix = quantize(&px, 96, 64, &PaletteOptions { colors: 64, dither: Dither::Diffusion, ..Default::default() }); let mut lossy_ix = ix.clone(); - lossy(&mut lossy_ix, &px, 80); + lossy(&mut lossy_ix, &px, 80, &[]); let runs = |ix: &Indexed| ix.indices.windows(2).filter(|w| w[0] != w[1]).count(); assert!(runs(&lossy_ix) < runs(&ix)); let size = |ix: &Indexed| gif::encode(ix, false).unwrap().len(); assert!(size(&lossy_ix) < size(&ix), "{} vs {}", size(&lossy_ix), size(&ix)); let mut none = ix.clone(); - lossy(&mut none, &px, 0); + lossy(&mut none, &px, 0, &[]); assert_eq!(none, ix); + // A fixed entry keeps its pixels and takes no others. + let fixed: Vec = (0..ix.palette.len()).filter_map(|i| u8::try_from(i).ok()).collect(); + let mut kept = ix.clone(); + lossy(&mut kept, &px, 100, &fixed); + assert_eq!(kept, ix); } #[test] diff --git a/crates/render/src/encode/web.rs b/crates/render/src/encode/web.rs index 2a26a336d1..3d572cf9ce 100644 --- a/crates/render/src/encode/web.rs +++ b/crates/render/src/encode/web.rs @@ -83,19 +83,24 @@ pub fn to_transparent(ix: &mut Indexed, mapped: impl Fn(usize) -> bool) -> Vec().0; for (row, src) in ix.indices.chunks_mut(w).zip(px.chunks(w)) { for x in 1..row.len() { let (prev, cur) = (row[x - 1], row[x]); - if prev == cur || ix.transparent.is_some_and(|t| t == prev || t == cur) { + if prev == cur || held[usize::from(prev)] || held[usize::from(cur)] { continue; } let (Some(c), Some(p)) = (src.get(x), ix.palette.get(prev as usize)) else { continue }; diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index dda132308f..2a554a3d92 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -726,6 +726,12 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b let a = art_effects_reach(symbols, n); Some(b.inflate(a, a)) } + // A spine can rotate a blend's keys and steps past their unrotated visual bounds. + NodeKind::Blend { .. } => { + let b = n.reach_bounds_with(symbols)?; + let a = live_content_reach(symbols, n); + vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n)) + } _ => { let b = n.visual_bounds_with(symbols)?; let b = match &n.kind { @@ -804,16 +810,43 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> b.inflate(o, o) } -/// `n`'s own visual box, type's grown to hold its glyphs ([`glyphs_box`]): what it draws when its -/// object effects leave it as it is (Revolve builds no art from type). +/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its +/// spine-placed keys and steps: what it draws when its object effects leave it as it is +/// (Revolve builds no art from type). fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { - let b = n.visual_bounds_with(symbols)?; + let b = match &n.kind { + NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)), + _ => n.visual_bounds_with(symbols), + }?; Some(match &n.kind { NodeKind::Text(t) => vectorcraft_geom::union_opt(Some(b), glyphs_box(t, n.appearance.outset())).unwrap_or(b), _ => b, }) } +/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects +/// run on the placed shapes, so their reach on the original keys need not cover what they paint. +/// Effect-free blends keep the quick rail envelope without evaluating their steps. +fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + let NodeKind::Blend { spec, .. } = &n.kind else { return None }; + if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath { + return None; + } + let mut has_effects = false; + n.walk(&mut |c| { + has_effects |= has_fx(c) + || has_object_fx(c) + || match &c.kind { + NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol), + _ => false, + }; + }); + if !has_effects { + return None; + } + effects::expand_live(Some(symbols.document()), n).iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds(symbols, c))) +} + /// The box of type `t`'s glyphs as laid out (its layout bounds, else laid out now), grown by its /// characters' strokes, miter spikes included, and by `outset`: on a path they stand above it and /// run past its ends, in an area they can hang past its frame, where its own box diff --git a/crates/tools/src/addons/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs index 0f674aead9..e8b228f86f 100644 --- a/crates/tools/src/addons/enclosing_lasso.rs +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool { let symbols = cx.doc.symbol_boxes(); let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); let mut ids = if let Some(region) = region { - enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline) + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline, !cx.guides) .into_iter() .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) .collect() diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 3e50415434..e397b1f9ed 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -76,6 +76,12 @@ pub struct DimensionTool { /// for that click (a snap or Shift can move the point away from it): placed with the pointer /// still at either, it is aligned. second: Option<(Point, Point)>, + /// While a Linear dimension is placed with its line on the level of another dimension's line: + /// the ends of that other line. A Smart Guide runs along the level across both lines. + level_guide: Option<(Point, Point)>, + /// While a dimension is placed: the lines of the visible, unlocked linear dimensions in the + /// document before its first preview ([`dimension_lines`]), which its line can line up with. + levels: Vec, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -285,6 +291,58 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false))) } +/// The line of a linear dimension already drawn: its ends and its direction. +type DimensionLine = ((Point, Point), Vec2); + +/// The lines of the visible, unlocked linear dimensions in the document. Bounded work, as in +/// [`on_dimensions`]. +fn dimension_lines(cx: &ToolContext) -> Vec { + fn visit(n: &Node, budget: &mut usize, out: &mut Vec) { + if *budget == 0 || !n.visible || n.locked { + return; + } + *budget -= 1; + if let Some(d) = &n.extras().dimension { + if d.mode == DimensionMode::Linear { + out.push((d.line_ends(), d.direction())); + } + return; + } + for c in n.children().into_iter().flatten().rev() { + visit(c, budget, out); + } + } + let (mut budget, mut out) = (20_000usize, vec![]); + for n in cx.doc.layers.iter().rev() { + visit(n, &mut budget, &mut out); + } + out +} + +/// Where the line of the linear dimension `d`, placed through `p`, lands on the level of one of +/// the `levels` that runs parallel to it, within `reach` of `p` across the line: the point to +/// place `d` through, and the ends of that other line. The nearest level wins, then the line +/// nearest `p` along it (none nearer than a line that `p` lies across). +fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> Option<(Point, (Point, Point))> { + if d.mode != DimensionMode::Linear { + return None; + } + let (u, normal) = (d.direction(), d.normal()); + let mut best: Option<(f64, f64, f64, (Point, Point))> = None; + for &(ends, direction) in levels { + if u.cross(direction).abs() > 1e-6 { + continue; + } + let shift = (ends.0 - p).dot(normal); + let (s0, s1) = ((ends.0 - p).dot(u), (ends.1 - p).dot(u)); + let along = if s0 * s1 <= 0.0 { 0.0 } else { s0.abs().min(s1.abs()) }; + if shift.is_finite() && along.is_finite() && shift.abs() <= reach && best.is_none_or(|(s, a, _, _)| (shift.abs(), along) < (s, a)) { + best = Some((shift.abs(), along, shift, ends)); + } + } + best.map(|(_, _, shift, ends)| (p + normal * shift, ends)) +} + /// The point of `edge` closest to `p`. fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { use vectorcraft_geom::kurbo::ParamCurveNearest; @@ -435,6 +493,7 @@ impl DimensionTool { p } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { + self.level_guide = None; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) && let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref()) @@ -462,10 +521,18 @@ impl DimensionTool { if d.resolve(cx.doc).is_err() { return vec![]; } - d.place(p); + // With Smart Guides on, a linear dimension's line lands on the level of a parallel + // dimension line already drawn within the Smart Guides snapping tolerance. The lines are + // read before the first preview, so the preview of this dimension is not one of them. + if !self.began { + self.levels = dimension_lines(cx); + } + let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None }; + d.place(level.map_or(p, |(on_level, _)| on_level)); if d.validate().is_err() { return vec![]; } + self.level_guide = level.map(|(_, ends)| ends); let mut actions = vec![]; if !self.began { actions.push(Action::Begin("Create Dimension".into())); @@ -495,6 +562,8 @@ impl DimensionTool { self.snap.clear(); self.snapped = None; self.second = None; + self.level_guide = None; + self.levels.clear(); } /// A plain click: picks a point or a line, or measures a circle's radius. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { @@ -664,6 +733,7 @@ impl Tool for DimensionTool { self.press = None; if self.pending.is_some() && self.began { self.began = false; + self.level_guide = None; vec![Action::Cancel] } else { vec![] @@ -741,6 +811,21 @@ impl Tool for DimensionTool { if linear_pick { out.extend(self.snap.guides().iter().cloned()); } + // A dimension line placed on the level of another: one alignment guide across both lines, + // unless Alignment Guides are off. + if cx.alignment_guides + && let (Some(d), Some((c, e))) = (&self.pending, self.level_guide) + { + let (a, b) = d.line_ends(); + let u = d.direction(); + let along = |q: &Point| q.to_vec2().dot(u); + let ends = [a, b, c, e]; + if let (Some(lo), Some(hi)) = + (ends.iter().min_by(|p, q| along(p).total_cmp(&along(q))), ends.iter().max_by(|p, q| along(p).total_cmp(&along(q)))) + { + out.push(Overlay::Line { a: *lo, b: *hi, color: cx.smart_guide_color, dashed: false }); + } + } out } } @@ -778,6 +863,21 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing"); } + /// Of two dimension lines on one level, a line the pointer lies across wins over a line whose + /// end is nearer the pointer. + #[test] + fn a_line_the_pointer_lies_across_wins_on_one_level() { + let pt = Point::new; + let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(200.0, 200.0), pt(300.0, 200.0), pt(250.0, 200.0), None); + let across = ((pt(0.0, 170.0), pt(400.0, 170.0)), Vec2::new(1.0, 0.0)); + let beside = ((pt(100.0, 170.0), pt(200.0, 170.0)), Vec2::new(1.0, 0.0)); + for levels in [[beside, across], [across, beside]] { + let (at, ends) = line_level(&levels, &d, pt(250.0, 172.0), 4.0).expect("on the level"); + assert!(at.distance(pt(250.0, 170.0)) < 1e-9, "{at:?}"); + assert_eq!(ends, across.0); + } + } + #[test] fn a_dropped_placement_press_does_not_commit_the_dimension() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 66cc842a53..9323bfb20f 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1674,7 +1674,7 @@ impl DirectSelectionTool { // marquee or an Alt-marquee, every object it touches, each whole (#8047). if enclosed || whole || self.group { (self.spine, self.spine_more) = (None, vec![]); - let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); + let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; @@ -1684,8 +1684,11 @@ impl DirectSelectionTool { } // Anchors inside the rect, on editable paths inside isolation mode. let mut sel: Vec<(NodeId, Vec)> = vec![]; + // Guide paths only while guides can be picked: not while they are locked or hidden (#8538). walk_pickable(cx.doc, cx.isolation, |n| { - if let NodeKind::Path { path, .. } = &n.kind { + if let NodeKind::Path { path, guide, .. } = &n.kind + && (cx.guides || !*guide) + { let v: Vec = path.anchors().filter(|(_, _, a)| r.contains(a.p)).map(|(s, i, _)| (s, i)).collect(); if !v.is_empty() { sel.push((n.id, v)); @@ -1773,7 +1776,7 @@ impl DirectSelectionTool { } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). - for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { + for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) { sel.push((id, vec![])); @@ -1785,7 +1788,8 @@ impl DirectSelectionTool { let mut crossed: Vec<(NodeId, Vec)> = vec![]; if !self.group { walk_pickable(cx.doc, cx.isolation, |n| { - if let NodeKind::Path { path, .. } = &n.kind + if let NodeKind::Path { path, guide, .. } = &n.kind + && (cx.guides || !*guide) && editable(n.id) { let segs = crossed_segments(path, r); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 50244eb260..4f3b795921 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2767,3 +2767,30 @@ fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() { let a = marquee(false); assert!(!selects(&a), "preview: {a:?}"); } + +/// #8538: while guides are locked or hidden (`guides` off), a Direct Selection marquee takes +/// neither the anchors nor the crossed segments of a guide path; while guides can be picked, it +/// takes them as on any path. +#[test] +fn a_marquee_skips_the_anchors_and_segments_of_guides_that_cannot_be_picked() { + let (mut d, id) = doc_with_rect(); + if let Some(NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *guide = true; + } + let (s, p) = (Selection::default(), paint()); + let marquee = |guides: bool, from: (f64, f64), to: (f64, f64)| { + let cx = ToolContext { guides, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)) + }; + let anchors = |items: Value| vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))]; + // Over the corner at (200, 100). + assert_eq!(marquee(false, (150.0, 50.0), (250.0, 150.0)), anchors(json!([])), "locked or hidden: no anchor"); + assert_eq!(marquee(true, (150.0, 50.0), (250.0, 150.0)), anchors(json!([{"id": id.0, "anchors": [[0, 1]]}])), "shown and unlocked"); + // Across the middle of the top edge. + let crossed = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.segments")); + assert!(!crossed(&marquee(false, (140.0, 80.0), (160.0, 120.0))), "locked or hidden: no segment"); + assert!(crossed(&marquee(true, (140.0, 80.0), (160.0, 120.0))), "shown and unlocked"); +} diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index b1077d5a12..0322c82ca3 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -525,10 +525,12 @@ impl Tool for PenTool { && let (Some((id, _, _, last, out)), Some(h)) = (self.active(cx), self.hover) { if cx.pen_rubber_band { + // The segment a click at `h` adds: it leaves the last anchor along its outgoing + // handle and arrives at the new corner anchor without a handle. let mut bp = BezPath::new(); bp.move_to(last); if out.distance(last) > 1e-9 { - bp.quad_to(out, h); + bp.curve_to(out, h, h); } else { bp.line_to(h); } diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index 710c39ae7a..7b804685b3 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -865,6 +865,27 @@ fn anchors_snap_to_smart_guides() { assert_eq!(a[1], Action::Preview("path.create".into(), json!({"anchors": [{"x": 100.0, "y": 100.0}]}))); } +/// The rubber band after a smooth anchor is the curve the click then adds: it leaves along the +/// anchor's outgoing handle and arrives at the new corner anchor without a handle, so the segment +/// keeps its shape when the anchor goes down (#8296). +#[test] +fn rubber_band_is_the_segment_a_click_adds() { + let (last, out) = (Point::new(60.0, 300.0), Point::new(110.0, 250.0)); + let sub = vectorcraft_geom::SubPath::new(vec![Anchor::corner(Point::new(10.0, 300.0)), Anchor::smooth(last, out)], false); + let (d, id, s) = drawing(sub); + let p = paint(); + let cx = ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(&d, &s, &p) }; + let h = Point::new(237.0, 361.0); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, h.x, h.y)); + let band: Vec<_> = + t.overlays(&cx).into_iter().filter_map(|o| if let Overlay::Path { path, .. } = o { Some(path.elements().to_vec()) } else { None }).collect(); + assert_eq!(band, vec![vec![vectorcraft_geom::PathEl::MoveTo(last), vectorcraft_geom::PathEl::CurveTo(out, h, h)]]); + // The click adds a corner anchor there: the segment drawn is the one previewed. + let a = click(&mut t, &cx, h.x, h.y, Mods::default()); + assert_eq!(a[1], Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": h.x, "y": h.y, "subpath": 0}))); +} + /// With Enable Rubber Band off, the preview segment is hidden but Measurement Labels still shows /// the D / Angle / dX / dY readout at the snapped point before the next click. #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 700c045d3f..079de9ed06 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -596,7 +596,12 @@ fn with_object_bounds(cx: &ToolContext, walk: impl FnOnce(&mut dyn FnMut(Node pub(crate) fn inside(cx: &ToolContext, r: Rect, ids: Vec) -> Vec { let symbols = cx.doc.symbol_boxes(); let within = |b: Rect| r.min_x() <= b.min_x() && b.max_x() <= r.max_x() && r.min_y() <= b.min_y() && b.max_y() <= r.max_y(); - ids.into_iter().filter(|id| cx.doc.node(*id).and_then(|n| n.geometric_bounds_with(&symbols)).is_some_and(within)).collect() + // Locked or hidden guides, which the marquee leaves out, don't count toward a group's box (#8538). + let measure = |n: &vectorcraft_doc::Node| match n.without_guides().filter(|_| !cx.guides) { + Some(art) => art.geometric_bounds_with(&symbols), + None => n.geometric_bounds_with(&symbols), + }; + ids.into_iter().filter(|id| cx.doc.node(*id).and_then(measure).is_some_and(within)).collect() } /// What of the bounding box is under the pointer. @@ -1199,7 +1204,7 @@ impl Tool for SelectionTool { if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) { return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline); + let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline, !cx.guides); let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside)); let ids = if enclosed { inside(cx, r, touched) } else { touched }; let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) })); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index a8e1f8acee..a39c528a1d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::testutil::*; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{Document, NodeKind, Selection}; /// While an opacity mask is edited, a press on a selected Shaper original shape moves it, over the /// art the group shows and over a part of the shape the group does not show. A press on an original @@ -146,6 +146,66 @@ fn a_press_where_a_mask_hides_a_selected_object_drags_it() { assert!(a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{a:?}"); } +/// #8538: while guides are locked or hidden (`guides` off), a Selection tool marquee that touches +/// only a guide path in a group selects nothing, so a drag can't move the guide; one that touches +/// the group's other member selects the group. With guides unlocked, the guide takes the group. +#[test] +fn a_marquee_over_a_locked_guide_in_a_group_selects_nothing() { + let mut d = Document::new(800.0, 600.0); + let l = d.layers[0].id; + let (gid, guide_id, art_id) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut guide = vectorcraft_doc::Node::path( + guide_id, + vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 120.0, 120.0)), + vectorcraft_doc::Appearance::default_art(), + ); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let art = vectorcraft_doc::Node::path( + art_id, + vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 100.0, 320.0, 120.0)), + vectorcraft_doc::Appearance::default_art(), + ); + d.insert(Some(l), 0, vectorcraft_doc::Node::group(gid, vec![std::sync::Arc::new(guide), std::sync::Arc::new(art)])).unwrap(); + let (none, p) = (Selection::default(), paint()); + let marquee = |guides: bool, x0: f64, x1: f64| { + let c = ToolContext { guides, ..cx(&d, &none, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, x0, 50.0)); + t.pointer(&c, &ev(PointerKind::Drag, x1, 110.0)); + let up = t.pointer(&c, &ev(PointerKind::Up, x1, 110.0)); + up.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "select.set" => Some(v["ids"].clone()), + _ => None, + }) + }; + assert_eq!(marquee(false, 90.0, 130.0), Some(json!([])), "locked: only the guide"); + assert_eq!(marquee(false, 290.0, 330.0), Some(json!([gid.0])), "locked: the group's art"); + assert_eq!(marquee(true, 90.0, 130.0), Some(json!([gid.0])), "unlocked: the guide"); +} + +/// #8538: an enclosing marquee measures a group without the locked or hidden guides in it, as the +/// marquee leaves them out: a group whose art lies inside is taken though a guide in it reaches +/// past the marquee. While guides can be picked, the guide counts. +#[test] +fn an_enclosing_marquee_measures_a_group_without_its_locked_guides() { + let mut d = Document::new(800.0, 600.0); + let l = d.layers[0].id; + let (gid, guide_id, art_id) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let square = |id, r| vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art()); + let mut guide = square(guide_id, Rect::new(500.0, 100.0, 520.0, 120.0)); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let art = square(art_id, Rect::new(100.0, 100.0, 120.0, 120.0)); + d.insert(Some(l), 0, vectorcraft_doc::Node::group(gid, vec![std::sync::Arc::new(guide), std::sync::Arc::new(art)])).unwrap(); + let (none, p) = (Selection::default(), paint()); + let r = Rect::new(50.0, 50.0, 200.0, 200.0); + assert_eq!(crate::select::inside(&ToolContext { guides: false, ..cx(&d, &none, &p) }, r, vec![gid]), [gid], "locked or hidden"); + assert!(crate::select::inside(&ToolContext { guides: true, ..cx(&d, &none, &p) }, r, vec![gid]).is_empty(), "shown and unlocked"); +} + /// #955: grabbed by an anchor and dropped near another object's anchor, the anchor lands /// exactly on it with Smart Guides, even where lining the bounds up would leave it beside it. #[test] diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 3f7006e536..e714b85aa2 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -329,3 +329,45 @@ fn common_tangents_previews_cancels_and_runs_on_ok() { assert_eq!((steps(&app), count(&app)), (n, nodes)); assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); } + +/// Common Tangents… on a point and an ellipse: every Tangents choice previews the same two lines +/// from the point, OK keeps them as one step, and a point inside the ellipse changes nothing and +/// says why. +#[test] +fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() { + let mut app = app(); + let oval = app.run("shape.ellipse", json!({"x": 180.0, "y": 120.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap(); + let point = + |app: &mut VectorcraftApp, x: f64, y: f64| app.run("path.create", json!({"anchors": [{"x": x, "y": y}]})).unwrap()["id"].as_u64().unwrap(); + let dot = point(&mut app, 40.0, 150.0); + app.run("select.set", json!({"ids": [oval, dot]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let (n, nodes) = (steps(&app), count(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + for (_, kind) in super::TANGENT_KINDS { + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "tangents".into(), json!(kind)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 2, "{kind}: the two lines from the point"); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "one undo step"); + + // A point inside the ellipse: nothing changes, and a message says why. + let inside = point(&mut app, 220.0, 150.0); + app.run("select.set", json!({"ids": [oval, inside]})).unwrap(); + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes)); + assert!(app.ui.status.contains("The point lies inside the path"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 07deadd05e..a05dcedb38 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -82,6 +82,7 @@ impl VectorcraftApp { slices: None, print_tiling: None, live_paint_gaps: None, + find_font: None, hidden_chars: Default::default(), spelling: Default::default(), selection_marks: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 161015a9c5..be5ff73c54 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -42,6 +42,10 @@ pub struct CanvasCache { pub print_tiling: Option, /// The gap lines View → Show Live Paint Gaps draws for (document uid, revision). pub live_paint_gaps: Option, + /// Type → Find Font's list of the document's fonts and whether the document misses one, for a + /// version of the document's content and of the available fonts: the dialog reads them every + /// frame. + pub find_font: Option, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::HiddenChars, @@ -117,6 +121,32 @@ pub type SliceCache = ((u64, u64), std::sync::Arc>); +/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether +/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked). +#[derive(Clone, Debug)] +pub struct FindFontCache { + /// The document and the content and fonts the answers were worked out from. + pub key: FontsKey, + pub fonts: std::sync::Arc>, + pub missing: Option, +} + +/// A document's uid, a version of its content (compared by identity) and the font database's +/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's +/// allocation, so a later version is never placed at the same address while the key is kept. +#[derive(Clone, Debug)] +pub struct FontsKey { + pub uid: u64, + pub doc: std::sync::Weak, + pub generation: u64, +} + +impl PartialEq for FontsKey { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc) + } +} + /// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they /// agree and `None` when they differ, with whether every one can be aligned. pub type PixelAligned = (Option, bool); diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index e54085e304..fcbee2132a 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1121,6 +1121,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_space((middle - BUTTON / 2.0 * row.len() as f32 - ui.cursor().min.x).max(0.0)); for &(s, slot) in row { let Some((rect, shown)) = slot_button(ui, &t, &press, slot, &mut actions) else { continue }; + crate::palette::note_spot(ui, rect, || crate::palette::SpotAt::Slot(Some(bar.name.clone()), slot.clone())); if edit_this { buttons.push((s, rect)); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 219fc4b2e5..da5b93a7bb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -547,8 +547,9 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] { } // The selected rows and Randomize's seed. Some(DialogKind::Recolor) => &["__seed", "__sel"], - // The view, zoom, download speed, selected color table entries and the preset name being typed. - Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__kbps", "__presetName", "__view", "__zoom"], + // The view, zoom, download speed, selected color table entries, the color table entry whose + // Color Picker opens and the preset name being typed. + Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__editColor", "__kbps", "__presetName", "__view", "__zoom"], // The link that keeps width and height in proportion. Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"], // The attention filter, the Keys section, the search text and the key being recorded. @@ -846,6 +847,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let focus_first = focus_first && !clicked; let spec = spec(&d.kind); + // Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to. + if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) { + modal::over_parent(ctx); + } if let Some(window) = spec.window { return window(app, ctx); } @@ -888,14 +893,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } + // When the dialog is taller than the window, its body scrolls, and the heading and the + // buttons stay in view. if let Some(body) = spec.body_with_actions { - match body(app, ui, &mut d) { + match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = (spec.body)(app, ui, &mut d); + cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -1076,6 +1083,9 @@ mod tests_perspective; #[cfg(test)] mod tests_modal; +#[cfg(test)] +mod tests_scroll; + #[cfg(test)] mod tests_rectangular_grid; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index b4abf8c6e2..c07f7af647 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 5ce5e64e53..758832cd92 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -384,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + super::modal::fits_itself(ui); let (side, values_w, button_w, stacked) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 1a08c4d377..3a977e76c6 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -4,7 +4,7 @@ use super::DialogSpec; use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets}; use egui::{RichText, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::dimension::DimensionOptions; +use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions}; pub const KIND: &str = "dimensionOptions"; pub(super) const SPEC: DialogSpec = DialogSpec { @@ -32,6 +32,10 @@ const UNITS: Choices = &[ ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; +/// The style of each `ARROWS` entry, in the same order. +const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None]; +/// The size of an Arrow Style preview: a line with the head at its right end. +const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")]; @@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, l }); changed } +/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in +/// the open list and in the closed field. +fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &str) -> bool { + const KEY: &str = "arrowStyle"; + let mut changed = false; + widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| { + let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default(); + let shown = ARROWS.iter().position(|(v, _)| *v == current); + let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { + if let Some(style) = ARROW_STYLES.get(i) { + crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); + } + }; + if let Some((value, _)) = + widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i)) + { + fields.insert(KEY.into(), json!(value)); + changed = true; + } + }); + changed +} fn number(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool { let mut changed = false; widgets::label_row(ui, tl!(label), 96.0, |ui| { @@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { color(ui, f, "lineColor"); }); ui.horizontal(|ui| { - choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS); + arrow_style(ui, f, "arrowStyle"); number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%"); }); }); @@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt"); changed |= color(ui, &mut f, "lineColor"); }); - ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS)); + ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle")); ui.horizontal(|ui| { changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt"); changed |= color(ui, &mut f, "textColor"); @@ -377,4 +404,56 @@ mod tests { assert!(text.contains(label), "{label}: {text}"); } } + + /// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line. + fn picture_before(out: &egui::FullOutput, name: &str) -> bool { + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())), + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)), + _ => {} + } + } + let (mut texts, mut pictures) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut pictures); + } + texts + .iter() + .filter(|(t, _)| t == name) + .any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y)) + } + + /// The frame `f` draws, once its previews are loaded. + fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)) + } + + /// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead, + /// drawn, before its name (#8049). + #[test] + fn arrow_style_shows_a_drawn_arrowhead() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("tool.options", json!({"tool":"dimension"})).unwrap(); + let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(picture_before(&out, "Filled"), "Tool Options"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap(); + let out = frame(&mut app, properties_section); + assert!(picture_before(&out, "Tick"), "Properties"); + } + + /// Each Arrow Style entry previews the style its value names. + #[test] + fn arrow_previews_follow_the_listed_styles() { + assert_eq!(ARROWS.len(), ARROW_STYLES.len()); + for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) { + assert_eq!(serde_json::to_value(style).unwrap(), json!(value)); + } + } } diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index c7bedbe2b1..c5acd64e18 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,8 +2,9 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons -//! stay in view. +//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its +//! heading and buttons stay in view. A window without such rows that is still too tall or too wide +//! for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -35,11 +36,97 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, add)?; - keep_rest(ctx, id, shown.response.rect.height()); + .show(ctx, |ui| { + // Just opened: what scrolls in the window starts at its top, wherever it was left when + // the window last closed. + if opened(ctx, id) { + ctx.data_mut(|m| { + m.insert_temp(id.with(TOP_ROWS_KEY), true); + m.insert_temp(id.with(TOP_WHOLE_KEY), true); + }); + } + // A window whose contents are wider than the screen has room for, or taller without + // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, + // so none of it is out of reach. The contents keep their ids whether the window scrolls + // or not, so a field being edited keeps its text when that changes. + let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); + let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); + let (r, contents) = if wide || tall { + let room = whole_room(ctx, margin); + let mut area = egui::ScrollArea::new([wide, tall]); + if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let out = area + .id_salt("modal-whole") + .max_width(room.x) + .max_height(room.y) + .min_scrolled_width(room.x) + .min_scrolled_height(room.y) + .show(ui, |ui| ui.scope_builder(scope, add).inner); + (out.inner, out.content_size) + } else { + let r = ui.scope_builder(scope, add).inner; + (r, ui.min_rect().size()) + }; + ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + r + })?; + keep_rest(ctx, id, shown.response.rect.height(), margin); shown.inner } +/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before, +/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard +/// Shortcuts). The window under it keeps where it was scrolled to. +pub(crate) fn over_parent(ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass)); +} + +/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, +/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). +fn opened(ctx: &egui::Context, id: Id) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| { + // The windows drawn in this pass so far and in the pass before. + let (at, now, prev) = m.get_temp::<(u64, Vec, Vec)>(Id::unique(LAST_KEY)).unwrap_or_default(); + let (mut now, prev) = if at == pass { + (now, prev) + } else if at.saturating_add(1) == pass { + (vec![], now) + } else { + (vec![], vec![]) + }; + let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); + now.push(id); + m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); + let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); + if last != u64::MAX && last.saturating_add(1) >= pass { + return false; + } + // Shown again as the window opened over it closed. + if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + return false; + } + // Opened over the window drawn last in the pass before, it holds that one; otherwise none. + match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { + Some(under) => { + m.insert_temp(id.with(HOLDS_KEY), under); + } + None => { + m.remove::(id.with(HOLDS_KEY)); + } + } + true + }) +} + +/// The room for the contents of a modal window with `margin` inside its frame. +fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { + (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) +} + /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { @@ -86,34 +173,158 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall -/// the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this +/// frame, and how tall the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; +/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to +/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). +const OWN_ROWS_KEY: &str = "modal-own-rows"; +const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. +const BODY_KEY: &str = "modal-body"; +/// Under a modal window's id: how large its contents would be without scrolling as a whole, this +/// frame. +const CONTENTS_KEY: &str = "modal-contents"; +/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on +/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). +const TALL_KEY: &str = "modal-tall"; +const WHOLE_KEY: &str = "modal-whole"; +/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, +/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so +/// they start at the top when they first do. +const SHOWN_KEY: &str = "modal-shown"; +const TOP_ROWS_KEY: &str = "modal-top-rows"; +const TOP_WHOLE_KEY: &str = "modal-top-whole"; +/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass +/// and of those drawn in the pass before it (`LAST_KEY`), and the pass +/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). +/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). +const LAST_KEY: &str = "modal-last"; +const OVER_KEY: &str = "modal-over"; +const HOLDS_KEY: &str = "modal-holds"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let id = ui.layer_id().id; - let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); - let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); - // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); - ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); - rows.inner + fits_itself(ui); + let (r, drawn, _) = rows(ui, salt, true, add); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); + r } -/// After modal window `id` is drawn `height` tall: keep the height of all of it but its -/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just -/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit -/// without waiting for input. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { - let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - if (used - rest).abs() > 0.5 { +/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing +/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window +/// scroll them again. +pub(crate) fn fits_itself(ui: &egui::Ui) { + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); +} + +/// The body of a shared dialog window. While the window would be taller than the screen has room +/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; +/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. +pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let id = ui.layer_id().id; + let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add); + if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { + ui.ctx().data_mut(|m| { + m.insert_temp(id.with(ROWS_KEY), drawn); + m.insert_temp(id.with(BODY_KEY), body); + }); + } + r +} + +/// Whether the [`body_rows`] of modal window `id` scroll in this frame. +fn body_scrolls(ctx: &egui::Context, id: Id) -> bool { + let own = ctx.data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); + !own && ctx.data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false) +} + +/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn. +pub(crate) fn body_view(ui: &egui::Ui) -> Option { + let id = ui.layer_id().id; + body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id)) +} + +/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on +/// which axes ([wide, tall]) the window scrolls as a whole. +#[cfg(test)] +pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option, [bool; 2]) { + let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id)); + (body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default()) +} + +/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`] +/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so +/// the list and its bar can be scrolled into view whole. +pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 { + body_view(ui).map_or(height, |view| view.min(height)) +} + +/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the +/// window as last drawn. +fn rows_room(ctx: &egui::Context, id: Id) -> f32 { + let rest = ctx.data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); + (ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0) +} + +/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their +/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. +/// Rows that do not `scroll` are as tall as they are, with no +/// scroll area (which would take the scroll requests of their fields from the window's). The rows +/// keep their ids either way, so a field being edited keeps its text when they start or stop +/// scrolling. +fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { + let id = ui.layer_id().id; + let room = rows_room(ui.ctx(), id); + let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); + if !scroll { + let rows = ui.scope_builder(scope, add); + let height = rows.response.rect.height(); + return (rows.inner, height, height); + } + // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. + let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); + if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); + (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) +} + +/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height +/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different +/// one (the window just opened, or what is around them changed), the next frame is drawn at once, +/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll +/// while the window would be taller than the screen has room for without them scrolling; a window +/// without rows that scroll scrolls as a whole while its contents would be taller than the room, +/// and any window scrolls sideways while its contents would be wider. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { + let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); + let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); + let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); + let room = whole_room(ctx, margin); + let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; + let tall = match (rows, body) { + (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, + _ => false, + }; + // A window that fits itself to the screen's height can still be too wide for it. + let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); + let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); + let mut repaint = tall != was_tall || whole != was_whole; + if let Some(rows) = rows { + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + repaint |= (used - rest).abs() > 0.5; + } + if repaint { ctx.request_repaint(); } } @@ -159,4 +370,159 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } + + /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal + /// windows named in `open` open, in that order: the first a heading and 60 rows, in + /// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is + /// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in + /// the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let add = |ui: &mut egui::Ui| { + for i in 0..60 { + ui.label(format!("Row {i}")); + } + }; + let mut events = Some(events); + let mut seen = false; + for _ in 0..frames { + *time += 1.0 / 60.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + for (i, &name) in open.iter().enumerate() { + if name.starts_with("over ") { + over_parent(ui.ctx()); + } + show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { + heading(ui, "Top"); + if i > 0 { + ui.label("Alert"); + } else if in_rows { + scrolled_rows(ui, "rows", add); + } else { + add(ui); + } + }); + } + }); + out.textures_delta.clear(); + seen = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) + } + _ => false, + }); + } + seen + } + + /// A wheel turn far down, at the middle of the 400×300 screen. + fn wheel_down() -> Vec { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel] + } + + #[test] + fn a_window_that_scrolled_opens_again_at_its_top() { + for in_rows in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + } + } + + #[test] + fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { + // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it + // did not close. A window that another replaced did close. Either may have shown an alert + // of its own, drawn after it in the same passes. + let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; + let mut wrong = vec![]; + for in_rows in [false, true] { + for (other, kept) in others { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { + wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); + } + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); + } + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + } + + #[test] + fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() { + // A field's edit state and the keyboard focus are kept under its id, so typing goes on into + // the same field when the screen's height changes whether the body or the window scrolls. + let mut wrong = vec![]; + for in_body in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let window = Id::unique("modal-field-id-test"); + let mut text = String::from("12"); + let mut time = 0.0; + let mut field = None; + let mut focus_given = false; + let mut seen = vec![]; + for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); + for i in 0..4 { + time += 1.0 / 60.0; + // Typed once the window has settled at this height. + let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] }; + let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + show(ui.ctx(), "Test", window, 0.0, 8, |ui| { + heading(ui, "Top"); + let mut add = |ui: &mut egui::Ui| { + let r = ui.text_edit_singleline(&mut text); + for i in 0..30 { + ui.label(format!("Row {i}")); + } + r.id + }; + field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); + }); + }); + out.textures_delta.clear(); + // The field is given the focus once, after the first frame; a resize that took it + // away would leave the keys typed after it untaken. + if let Some(id) = field.filter(|_| !focus_given) { + ctx.memory_mut(|m| m.request_focus(id)); + focus_given = true; + } + } + let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; + let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); + seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some())); + } + let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)]; + let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect(); + if seen != want { + wrong.push((in_body, seen)); + } + } + // Only the short screen scrolls, and the field keeps its focus and takes each key. + assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong"); + } } diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 9a9da0c164..b64815b8dd 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index ebaad1749a..dd8db94418 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d), "Output" => output(ui, d, &preview), "Graphics" => graphics(ui, d), diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 54ff2b7d0a..6ff967f95a 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -2,8 +2,9 @@ //! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views, //! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8, //! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, -//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color -//! and Restore Generated Table), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, +//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color, +//! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker, +//! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, //! slices and HTML output, and presets. //! //! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with @@ -11,7 +12,8 @@ //! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed), //! `__color` (the colour table's selected colour, by source: the one Lock, Transparent and Web //! Shift edit, and where a Shift-click range starts), `__colors` (every selected color, by source, -//! which Delete Color deletes; when it is empty, `__color` alone), `__presetName` (shown while saving a +//! which Delete Color deletes; when it is empty, `__color` alone), `__editColor` (a source color: +//! the Color Picker opens on it, as a double-click on its swatch opens it), `__presetName` (shown while saving a //! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K), //! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`, //! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and @@ -55,6 +57,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; +/// The narrowest the panes get in a narrow window. +const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -533,12 +537,22 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { { app.status(e); } + take_shift(d); let settings = settings_of(app, d); let mut browser = false; - ui.horizontal_top(|ui| { + // In a window too narrow for both, the panes are narrower, so the settings beside them and the + // buttons below stay in view. The room is the screen's (the window's own width follows what it + // drew last), less a column for the bar of the body while it scrolls; the settings column is as + // wide as it was drawn last. + let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 }; + let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar; + let rest_id = egui::Id::unique("save-for-web-beside-panes"); + let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); + let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); + let row = ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - browser = preview_area(app, ui, d, &settings); + ui.set_width(preview_w); + browser = preview_area(app, ui, d, &settings, preview_w); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -546,23 +560,33 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + let drawn = row.response.rect.width() - preview_w; + if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 { + ui.ctx().request_repaint(); + } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); } + // A double-clicked swatch (or an agent's `__editColor`) opens the Color Picker last, over the + // dialog as it now is. + if let Some(source) = d.fields.remove("__editColor").and_then(|v| v.as_str().map(String::from)) { + let start = d.fields.remove("__editStart").and_then(|v| v.as_str().map(String::from)).unwrap_or_else(|| source.clone()); + edit_color(d, &source, &start); + } false } -/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was -/// clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { +/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in +/// Browser was clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { @@ -607,6 +631,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set } ui.add_space(6.0); let mut browser = false; + // Preview in Browser goes on a row of its own when the panes are too narrow for it beside the + // two lists (its width as `widgets::secondary_button` draws it). + let label = tl!("Preview in Browser"); + let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0); + let mut beside = false; + let mut button = |ui: &mut egui::Ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label)); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + }; ui.horizontal(|ui| { let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2); let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0)); @@ -623,11 +658,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set { d.fields.insert("__kbps".into(), json!(s)); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser"))); - browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); - }); + beside = ui.available_width() >= button_w; + if beside { + button(ui); + } }); + if !beside { + ui.add_space(4.0); + ui.horizontal(button); + } browser } @@ -732,7 +771,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& presets_row(app, ui, d, s); optimize_rows(ui, d, s, &art_key(app)); widgets::divider(ui); - egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| { + let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0); + egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| { form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options); }; @@ -1057,7 +1097,9 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) { /// ones with a square, web-safe ones with a diamond, transparent ones over the grid), the buttons /// that edit the selected colour, Delete Color and the table's menu, plus the sort order. A click /// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click -/// (Command-click on macOS) adds or removes one. Returns an error for a deletion that would leave +/// (Command-click on macOS) adds or removes one; a double-click on an opaque color asks for the +/// Color Picker (`__editColor`), and a color shifted by hand shows its source color at the upper +/// left and its new color at the lower right. Returns an error for a deletion that would leave /// no color. fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> { let t = Tokens::get(ui.ctx()); @@ -1086,15 +1128,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re .colors .iter() .map(|c| (*c, false)) - .chain(shot.mapped.iter().map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false }, true))) + .chain( + shot.mapped + .iter() + .map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false, shifted: false }, true)), + ) .collect(); const CELL: f32 = 15.0; let per_row = ((SIDE_W - 8.0) / (CELL + 2.0)).floor().max(1.0) as usize; let lines = rows.len().div_ceil(per_row).max(1); - let (area, resp) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::click()); + let (area, _) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::hover()); // The colors that can be selected, in table order (for Shift-click ranges). let order: Vec = rows.iter().filter(|(c, mapped)| !c.transparent || *mapped).map(|(c, _)| hex(c.source)).collect(); let mut clicked = None; + let mut edit = None; let p = ui.painter(); for (i, (c, mapped)) in rows.iter().enumerate() { let r = egui::Rect::from_min_size( @@ -1113,6 +1160,15 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re } } else { p.rect_filled(r, 0.0, fill); + if c.shifted { + // Shifted by hand: the source color at the upper left, the new one at the lower right. + let [red, g, b] = c.source; + p.add(egui::Shape::convex_polygon( + vec![r.left_top(), r.right_top(), r.left_bottom()], + egui::Color32::from_rgb(red, g, b), + egui::Stroke::NONE, + )); + } } let mark = if c.color.iter().map(|v| u32::from(*v)).sum::() > 380 { egui::Color32::BLACK } else { egui::Color32::WHITE }; if c.locked { @@ -1130,18 +1186,37 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re let pickable = !c.transparent || *mapped; let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source))); p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside); - if pickable && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) { + if !pickable { + continue; + } + let resp = ui.interact(r, swatch_id(&hex(c.source)), egui::Sense::click()); + if resp.clicked() { clicked = Some(hex(c.source)); } + // A double-click edits an opaque color: the picker opens on the color as shown, or on the + // source color for a color already shifted by hand. + if resp.double_clicked() && !c.transparent { + edit = Some((hex(c.source), hex(if c.shifted { c.source } else { c.color }))); + } } if let Some(c) = clicked { let m = ui.input(|i| i.modifiers); pick(d, &order, &c, m.shift, m.command); } + if let Some((source, start)) = edit { + d.fields.insert("__editColor".into(), json!(source)); + d.fields.insert("__editStart".into(), json!(start)); + } + let shifted = |c: &str| table.shifted.keys().any(|k| k.eq_ignore_ascii_case(c)); + // The colors the table shows, by source: Lock, Transparent, Web Shift and Delete Color act only + // on these. + let palette: Vec = + shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); + let shown = palette.iter().any(|p| p.eq_ignore_ascii_case(&selected)); ui.add_space(4.0); let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected)); ui.horizontal(|ui| { - ui.add_enabled_ui(!selected.is_empty(), |ui| { + ui.add_enabled_ui(shown, |ui| { for (list, on_label, off_label) in [ ("transparent", tl!("Restore"), tl!("Transparent")), ("webShift", tl!("Unshift"), tl!("Web Shift")), @@ -1152,21 +1227,30 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re "webShift" => &table.web_shift, _ => &table.locked, }; - let is_on = on(current); - if widgets::flat_button(ui, if is_on { on_label } else { off_label }, 88.0).clicked() { + // A color shifted by hand stays locked until it is unshifted. + let fixed = list == "locked" && shifted(&selected); + let is_on = on(current) || fixed; + let label = if is_on { on_label } else { off_label }; + if ui.add_enabled(!fixed, |ui: &mut egui::Ui| widgets::flat_button(ui, label, 88.0)).clicked() { toggle(d, list, &selected, !is_on); + // Web Shift replaces a shift by hand. + if list == "webShift" && !is_on { + unshift(d, &selected); + } } } }); }); - // Delete Color (the button and the table's menu) and Restore Generated Table. - let (mut delete, mut restore) = (false, false); + // Delete Color (the button and the table's menu) and Restore Generated Table. Delete Color + // takes only selected colors the table shows (`palette`, by source). + let deletable = !selected_in(d, &palette).is_empty(); + let (mut delete, mut restore, mut unshift_all) = (false, false, false); ui.horizontal(|ui| { - delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, !picked.is_empty(), 24.0).clicked(); + delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, deletable, 24.0).clicked(); let menu = widgets::icon_button(ui, "menu", tl!("Color Table"), false, 24.0); let open = menu.clicked(); let _ = widgets::popover(&menu, open, |ui| { - if widgets::menu_item(ui, tl!("Delete Color"), !picked.is_empty(), false) { + if widgets::menu_item(ui, tl!("Delete Color"), deletable, false) { delete = true; ui.close(); } @@ -1174,6 +1258,10 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re restore = true; ui.close(); } + if widgets::menu_item(ui, tl!("Unshift All Colors"), !table.shifted.is_empty() || !table.web_shift.is_empty(), false) { + unshift_all = true; + ui.close(); + } }); }); let sort = table.sort; @@ -1188,14 +1276,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re if restore { restore_table(d); } + if unshift_all { + unshift_all_colors(d); + } if delete { - let palette: Vec = - shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); delete_colors(d, &palette)?; } Ok(()) } +/// The selected colors (by source) that `palette`, the colors the table shows, holds. +pub(super) fn selected_in(d: &Dialog, palette: &[String]) -> Vec { + selection(d).into_iter().filter(|c| palette.iter().any(|p| p.eq_ignore_ascii_case(c))).collect() +} + /// The colour table's selected colors, by source: `__colors`, else `__color`. pub(super) fn selection(d: &Dialog) -> Vec { let many: Vec = @@ -1245,11 +1339,14 @@ pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, c /// Delete Color: the selected colors join the color table's `deleted` list and leave its other /// lists. The first deletion fixes the palette (`customPalette`) to `palette`, the table's colors /// (by source) with the deleted ones, so the colors left do not change. A deletion that leaves no -/// color, or only colors mapped to transparent, is refused with nothing changed. The selection is -/// cleared. +/// color, or only colors mapped to transparent, is refused with nothing changed. Only selected +/// colors that `palette` holds are deleted; when it holds none of them, the table is left as it is +/// and the selection is cleared. The selection is cleared after a deletion too. pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), String> { - let picked = selection(d); + let picked = selected_in(d, palette); if picked.is_empty() { + d.fields.remove("__colors"); + d.fields.remove("__color"); return Ok(()); } let list = |d: &Dialog, key: &str| -> Vec { @@ -1285,6 +1382,9 @@ pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), St } } } + for c in &picked { + unshift(d, c); + } set_table(d, "customPalette", json!(custom)); set_table(d, "deleted", json!(deleted)); d.fields.remove("__colors"); @@ -1299,6 +1399,71 @@ pub(super) fn restore_table(d: &mut Dialog) { set_table(d, "customPalette", json!([])); } +/// The id of the color table's swatch for the source color `source` (`#rrggbb`). +pub(super) fn swatch_id(source: &str) -> egui::Id { + egui::Id::unique(("sfw-swatch", source.to_ascii_lowercase())) +} + +/// The field of the Color Picker's OK over Save for Web: the color the edited swatch shifts to. +const SHIFT_TO: &str = "__shiftTo"; + +/// The Color Picker over the dialog for the color table's source color `source`, on `start`; its +/// OK shifts the color ([`shift_color`]) and its Cancel leaves the table as it was. Nothing opens +/// when either is not a color. +pub(super) fn edit_color(d: &mut Dialog, source: &str, start: &str) { + let (Some(_), Some(c)) = (vectorcraft_color::Color::from_hex(source), vectorcraft_color::Color::from_hex(start)) else { return }; + d.fields.insert("__shiftSource".into(), json!(source)); + *d = super::color_picker::over_effect(d, SHIFT_TO, c); +} + +/// Back from the Color Picker: its OK's color shifts the color it was opened for. +fn take_shift(d: &mut Dialog) { + let source = d.fields.remove("__shiftSource"); + if let (Some(to), Some(source)) = (d.fields.remove(SHIFT_TO), source) + && let (Some(to), Some(source)) = (to.as_str(), source.as_str()) + { + shift_color(d, source, to); + } +} + +/// Shift the source color `source` to `to` (`colorTable.shifted`), wherever it is in the image; it +/// is no longer web-shifted. Picking the source color itself takes the shift away. The color +/// becomes the selection. Nothing changes when either is not a color. +pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) { + let hex = |h: &str| vectorcraft_color::Color::from_hex(h).map(|c| c.to_hex()); + let (Some(source), Some(to)) = (hex(source), hex(to)) else { return }; + unshift(d, &source); + if to != source { + let mut map = shifts(d); + map.insert(source.clone(), json!(to)); + set_table(d, "shifted", Value::Object(map)); + } + toggle(d, "webShift", &source, false); + d.fields.insert("__colors".into(), json!([source])); + d.fields.insert("__color".into(), json!(source)); +} + +/// The `colorTable.shifted` field. +fn shifts(d: &Dialog) -> Map { + d.fields.get("colorTable").and_then(|t| t.get("shifted")).and_then(Value::as_object).cloned().unwrap_or_default() +} + +/// Take the shift by hand of the source color `source` away. +pub(super) fn unshift(d: &mut Dialog, source: &str) { + let mut map = shifts(d); + let before = map.len(); + map.retain(|k, _| !k.eq_ignore_ascii_case(source)); + if map.len() != before { + set_table(d, "shifted", Value::Object(map)); + } +} + +/// Unshift All Colors: no color is shifted by hand or web-shifted. +pub(super) fn unshift_all_colors(d: &mut Dialog) { + set_table(d, "shifted", json!({})); + set_table(d, "webShift", json!([])); +} + /// Add `color` to the colour table's `list`, or take it out. pub(super) fn toggle(d: &mut Dialog, list: &str, color: &str, add: bool) { let mut v: Vec = d.fields.get("colorTable").and_then(|t| t.get(list)).and_then(Value::as_array).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index cb515c8944..edfb66e7f4 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -429,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Compression" => compression(ui, d), "Marks and Bleeds" => marks_and_bleeds(app, ui, d), "Output" => output(ui, d), diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..e6c9a6ee0a 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { + crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 146e02c6eb..9d73ad769d 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -8,7 +8,8 @@ //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; //! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an -//! existing symbol). Help: +//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art). +//! Help: //! . use serde_json::{Map, Value, json}; @@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic" pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; -/// Open Symbol Options to name a new symbol made from the selection. -pub fn open(app: &mut VectorcraftApp) -> Result { +/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves +/// the selection as ordinary art instead of replacing it with an instance. +pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result { let st = app.session.active().ok_or("no document open")?; if st.selection.is_empty() { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = - json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false }); + let mut fields = json!({ + "name": name, + "exportType": "movieClip", + "type": "dynamic", + "registration": 4, + "alignToPixelGrid": false, + "__edit": false, + "__keepArt": keep_art, + }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } else { let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); + if d.bool("__keepArt") { + params["keepArt"] = json!(true); + } app.run("symbol.new", params) }; if r.is_ok() { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index cad38bb984..00b45e0db7 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) } -/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. +/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out. fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; screen.run(app, vec![]); let out = screen.run(app, vec![]); let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; - let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); + // W is left of H on their row (the tree lists its nodes in no particular order). + let w = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))) + .min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0))); screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index e27f4b766c..a965977b14 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -783,6 +783,177 @@ fn colour_table_selection_and_delete_color() { assert_eq!((&d.fields["colorTable"]["deleted"], &d.fields["colorTable"]["customPalette"]), (&json!([]), &json!([]))); } +/// Delete Color takes only selected colors the table shows: a selection the table no longer holds +/// (after a change of reduction or color count, or set through `ui.dialog.set`) deletes nothing, +/// fixes no palette and is cleared, and a selection partly in the table deletes only what it shows. +#[test] +fn delete_color_skips_selected_colors_the_table_does_not_show() { + let mut d = Dialog::new(save_for_web::KIND, json!({})); + let shown: Vec = ["#000000", "#111111"].map(String::from).to_vec(); + let table = |d: &Dialog, key: &str| d.fields.get("colorTable").and_then(|t| t.get(key)).cloned(); + d.fields.insert("__colors".into(), json!(["#ABCDEF"])); + d.fields.insert("__color".into(), json!("#abcdef")); + assert!(save_for_web::selected_in(&d, &shown).is_empty()); + save_for_web::delete_colors(&mut d, &shown).unwrap(); + assert_eq!((table(&d, "customPalette"), table(&d, "deleted")), (None, None)); + assert!(!d.fields.contains_key("__colors") && !d.fields.contains_key("__color")); + d.fields.insert("__colors".into(), json!(["#abcdef", "#111111"])); + assert_eq!(save_for_web::selected_in(&d, &shown), ["#111111"]); + save_for_web::delete_colors(&mut d, &shown).unwrap(); + assert_eq!((table(&d, "customPalette"), table(&d, "deleted")), (Some(json!(shown)), Some(json!(["#111111"])))); +} + +/// A shift by hand replaces a web shift and selects the color; a shift to the color itself takes it +/// away; Unshift All Colors clears both kinds; Delete Color takes a deleted color's shift away. +#[test] +fn colour_table_shift_unshift_and_unshift_all() { + let mut d = Dialog::new(save_for_web::KIND, json!({})); + save_for_web::toggle(&mut d, "webShift", "#123456", true); + save_for_web::shift_color(&mut d, "#123456", "#FF8800"); + assert_eq!(d.fields["colorTable"], json!({"webShift": [], "shifted": {"#123456": "#ff8800"}})); + assert_eq!(save_for_web::selection(&d), ["#123456"]); + // Not a color: nothing changes. + let before = d.fields.clone(); + save_for_web::shift_color(&mut d, "nope", "#000000"); + save_for_web::shift_color(&mut d, "#123456", "nope"); + assert_eq!(d.fields, before); + save_for_web::shift_color(&mut d, "#ABCDEF", "#00ff00"); + save_for_web::shift_color(&mut d, "#123456", "#123456"); + assert_eq!(d.fields["colorTable"]["shifted"], json!({"#abcdef": "#00ff00"})); + save_for_web::toggle(&mut d, "webShift", "#222222", true); + save_for_web::unshift_all_colors(&mut d); + assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["webShift"]), (&json!({}), &json!([]))); + let order: Vec = ["#000000", "#222222"].map(String::from).to_vec(); + save_for_web::shift_color(&mut d, "#222222", "#ffffff"); + save_for_web::delete_colors(&mut d, &order).unwrap(); + assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["deleted"]), (&json!({}), &json!(["#222222"]))); +} + +/// One frame of `app` in `ctx`, 50 ms after the last. +fn tick(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let time = ctx.input(|i| i.time) + 0.05; + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// Double-click the color table's swatch of the source color `source`. +fn double_click_swatch(app: &mut VectorcraftApp, ctx: &egui::Context, source: &str) { + for _ in 0..3 { + tick(app, ctx, vec![]); + } + let pos = ctx.read_response(save_for_web::swatch_id(source)).unwrap_or_else(|| panic!("no swatch for {source}")).rect.center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + tick(app, ctx, vec![egui::Event::PointerMoved(pos), button(true)]); + tick(app, ctx, vec![button(false)]); + tick(app, ctx, vec![button(true)]); + tick(app, ctx, vec![button(false)]); + tick(app, ctx, vec![]); +} + +/// The color the open Color Picker shows. +fn picker_color(app: &VectorcraftApp) -> Option { + let d = app.ui.dialog.as_ref()?; + assert_eq!(d.kind, "colorPicker", "the Color Picker is open"); + d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value).map(|c| c.to_hex()) +} + +/// A double-click on a swatch opens the Color Picker on its color. Cancel changes nothing; OK +/// shifts the color in the table and the saved file. A double-click on a shifted swatch opens the +/// picker on the source color, and Web Shift replaces the shift by hand. +#[test] +fn double_clicking_a_swatch_shifts_its_color() { + let dir = vectorcraft_testkit::temp_dir("sfw-shift-color"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let shifted = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| d.fields["colorTable"]["shifted"].clone()); + double_click_swatch(&mut app, &ctx, "#0000ff"); + assert_eq!(picker_color(&app).as_deref(), Some("#0000ff")); + crate::dialogs::cancel(&mut app); + tick(&mut app, &ctx, vec![]); + assert_eq!((kind(&app), shifted(&app)), (Some(save_for_web::KIND), Some(json!({}))), "Cancel shifts nothing"); + double_click_swatch(&mut app, &ctx, "#0000ff"); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app).unwrap(); + tick(&mut app, &ctx, vec![]); + assert_eq!((kind(&app), shifted(&app)), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"}))), "OK shifts the color"); + // The shifted swatch opens on its source color. + double_click_swatch(&mut app, &ctx, "#0000ff"); + assert_eq!(picker_color(&app).as_deref(), Some("#0000ff")); + crate::dialogs::cancel(&mut app); + // Web Shift replaces the shift by hand. + click_text(&mut app, "Web Shift"); + let t = app.ui.dialog.as_ref().unwrap().fields["colorTable"].clone(); + assert_eq!((&t["shifted"], &t["webShift"]), (&json!({}), &json!(["#0000ff"]))); + // Shifted again, the color reaches the saved file and is remembered. + double_click_swatch(&mut app, &ctx, "#0000ff"); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app).unwrap(); + tick(&mut app, &ctx, vec![]); + let r = confirm(&mut app).unwrap(); + let image = image::open(r["path"].as_str().unwrap()).unwrap().to_rgba8(); + assert_eq!((image.get_pixel(50, 20).0, image.get_pixel(20, 14).0), ([0, 255, 0, 255], [204, 51, 0, 255])); + let remembered = app.session.last_web_settings().color_table; + assert_eq!((remembered.shifted.get("#0000ff").map(String::as_str), remembered.web_shift.len()), (Some("#00ff00"), 0)); +} + +/// `ui.dialog.set` accepts `__editColor`, and the next frame opens the Color Picker on that color, +/// whose OK shifts it. +#[test] +fn dialog_set_edit_color_opens_the_color_picker() { + let dir = vectorcraft_testkit::temp_dir("sfw-edit-color-set"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("gif")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "__editColor", "value": "#0000ff"})); + let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") }; + assert_eq!(r["ok"], true, "{r}"); + tick(&mut app, &ctx, vec![]); + assert_eq!(picker_color(&app).as_deref(), Some("#0000ff")); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app).unwrap(); + tick(&mut app, &ctx, vec![]); + let shifted = app.ui.dialog.as_ref().map(|d| d.fields["colorTable"]["shifted"].clone()); + assert_eq!((kind(&app), shifted), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"})))); +} + +/// Lock, Transparent and Web Shift are off while the selected color (`__color`) is one the table +/// no longer shows, so a click adds it to no list; with a color the table shows, Lock locks it. +#[test] +fn table_buttons_skip_a_selected_color_the_table_does_not_show() { + let dir = vectorcraft_testkit::temp_dir("sfw-stale-anchor"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + let table = |app: &VectorcraftApp| app.ui.dialog.as_ref().and_then(|d| d.fields.get("colorTable").cloned()).unwrap_or_default(); + let has = |app: &VectorcraftApp, list: &str, c: &str| table(app)[list].as_array().is_some_and(|l| l.iter().any(|v| v == c)); + set(&mut app, "__color", json!("#abcdef")); + for label in ["Lock", "Transparent", "Web Shift"] { + click_text(&mut app, label); + } + for list in ["locked", "transparent", "webShift"] { + assert!(!has(&app, list, "#abcdef"), "{list}: {}", table(&app)); + } + set(&mut app, "__color", json!("#0000ff")); + click_text(&mut app, "Lock"); + assert!(has(&app, "locked", "#0000ff"), "{}", table(&app)); +} + /// Click the dialog's text `label` with the pointer (frames a quarter second apart). fn click_text(app: &mut VectorcraftApp, label: &str) { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs new file mode 100644 index 0000000000..bb013802ed --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -0,0 +1,449 @@ +//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of +//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests +//! can find it. + +use egui::{Pos2, Rect, Shape, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +type Open = fn(&mut VectorcraftApp); + +/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls +/// ([`modal::scrolling`]). +struct Shown { + shapes: Vec, + window: Rect, + body: Option, + whole: [bool; 2], +} + +/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away +/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right +/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists +/// inside it) and draw it until it settles again. +fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid()); + open(&mut app); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let window = |ctx: &egui::Context| { + ctx.memory(|m| { + m.areas() + .visible_layer_ids() + .into_iter() + .filter(|l| l.order == egui::Order::Foreground) + .filter_map(|l| Some((l.id, m.area_rect(l.id)?))) + .max_by(|a, b| a.1.area().total_cmp(&b.1.area())) + }) + .unwrap_or((egui::Id::NULL, Rect::NOTHING)) + }; + let mut time = 0.0; + let mut frames = |app: &mut VectorcraftApp, first: Vec| { + let mut first = Some(first); + let mut shapes = vec![]; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + shapes = std::mem::take(&mut out.shapes); + } + shapes + }; + let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]); + if scroll { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(-5000.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let (id, w) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole }; + // On the window's upright bar, else on its body's bar, else on its sideways bar, else at + // its right edge. + let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width()); + let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); + shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); + } + let (id, window) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + Shown { shapes, window, body, whole } +} + +/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or +/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip. +fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec { + fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec) { + match s { + Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => { + let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) }; + if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) { + out.push(r.rect); + } + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out)); + out.retain(|r| shown.window.expand(0.5).contains_rect(*r)); + out +} + +/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is +/// drawn (a list inside the body draws its bar further left). +fn body_bar(shown: &Shown) -> Option { + let view = shown.body?; + bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right())) +} + +/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that +/// runs most of the window's height (lists inside it are shorter). +fn whole_bar(shown: &Shown) -> Option { + let w = shown.window; + bars(shown, false, true) + .into_iter() + .filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height()) + .max_by(|a, b| a.height().total_cmp(&b.height())) +} + +/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and +/// its clip). +fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> { + texts(shown) + .into_iter() + .filter(|(s, ..)| labels.contains(&s.as_str())) + .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) + .collect() +} + +#[test] +fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() { + let opens: [(&str, Open, &[&str]); 7] = [ + ("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]), + ("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]), + ("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]), + ( + "Save PDF", + |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + }, + &["Cancel"], + ), + ( + "Save for Web", + |app| { + save_for_web::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ("Export for Screens", export_for_screens::open, &["Cancel"]), + ( + "Print", + |app| { + print::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window); + assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + let found = buttons(&shown, screen, labels); + assert_eq!(found.len(), labels.len(), "{name}: {found:?}"); + assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}"); + assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole"); + let bar = body_bar(&shown); + assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true)); + } +} + +#[test] +fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() { + // The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their + // own; in a short window those lists are no taller than the body shows, so each list and its + // bar can be scrolled into view whole. + let opens: [(&str, Open); 3] = [ + ("Save for Web", |app| { + save_for_web::open(app).unwrap(); + }), + ("Print", |app| { + print::open(app).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleed")); + } + }), + ("Save PDF", |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleeds")); + } + }), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0)); + let mut wrong = vec![]; + for (name, open) in opens { + let shown = show_in(open, screen.size(), false); + let Some(body) = body_bar(&shown) else { + wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false))); + continue; + }; + // The tracks of the lists' bars, seen or not: left of the body's bar and inside the window + // (a list taller than the body runs past the window's bottom). + let lists: Vec = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect(); + let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max); + if tallest == 0.0 || tallest > body.height() + 0.5 { + wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false))); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() { + let open: Open = |app| { + save_for_web::open(app).unwrap(); + }; + // The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%. + let mut wrong = vec![]; + for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] { + let screen = Rect::from_min_size(Pos2::ZERO, size); + let shown = show_in(open, size, false); + let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"]; + let found = buttons(&shown, screen, &labels); + if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) { + wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window)); + } + if body_bar(&shown).is_none() || shown.whole != [false; 2] { + wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole)); + } + // The controls under the narrower panes stay in their column, left of the settings. + let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right()); + let settings = text_rects(&shown, "Format:").first().map(|r| r.left()); + if !matches!((controls, settings), (Some(c), Some(s)) if c < s) { + wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})")); + } + // Preview in Browser is right of the download speed list or on a row below it, not over it. + let button = text_rects(&shown, "Preview in Browser").first().copied(); + let speed = text_rects(&shown, "56.6 Kbps").first().copied(); + if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) { + wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The rectangles of the texts `label` the dialog drew. +fn text_rects(shown: &Shown, label: &str) -> Vec { + fn walk(s: &Shape, label: &str, out: &mut Vec) { + match s { + Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out)); + out +} + +#[test] +fn a_window_too_large_for_the_screen_scrolls_as_a_whole() { + let opens: [(&str, Open, &[&str]); 4] = [ + ("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]), + ("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]), + ("New Document", new_document::open, &["Create", "Close"]), + ("Find Font", crate::find_font::open, &["Done"]), + ]; + // The app window's smallest size. + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!( + tall.window.height() > screen.height() || tall.window.width() > screen.width(), + "{name}: the dialog is larger than the small window ({:?})", + tall.window + ); + assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + assert!(shown.whole[1], "{name}: the dialog scrolls as a whole"); + assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true)); + // The buttons can sit outside the part in view; each is in view at the top or scrolled to + // the end. + let scrolled = show_in(open, screen.size(), true); + let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels)); + for label in labels { + let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen); + assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}"); + } + } +} + +#[test] +fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { + // Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import + // Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut time = 0.0; + // Draws 12 frames, the first with `events`; returns whether the heading can be seen. + let mut heading_seen = |app: &mut VectorcraftApp, events: Vec| { + let mut events = Some(events); + let mut seen = false; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] }; + seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen); + } + seen + }; + let wheel = |at: Pos2| { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(at), wheel] + }; + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top"); + // On the window's bar, inside its 20 pt margin. + let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen); + assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away"); + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n"; + crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND)); + heading_seen(&mut app, vec![]); + cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again"); + assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to"); + cancel(&mut app); + heading_seen(&mut app, vec![]); + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top"); +} + +/// Open Import Shortcut Set on a set of two shortcuts. +fn open_shortcut_import(app: &mut VectorcraftApp) { + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; + crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); +} + +#[test] +fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { + // Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An + // 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt. + let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0)); + assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window); + assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll"); + let shown = show_in(open_shortcut_import, screen.size(), false); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert_eq!(shown.whole, [true, false], "it scrolls sideways only"); + let sideways: Vec = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect(); + assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); +} + +#[test] +fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() { + // In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right + // edge, the text drawn furthest right in a large window can be seen. + let opens: [(&str, Open); 3] = [ + ("Import Shortcut Set", open_shortcut_import), + ("Keyboard Shortcuts", crate::shortcut_editor::open), + ("Preferences", |app| crate::prefs_dialog::open(app, None)), + ]; + let mut wrong = vec![]; + for (name, open) in opens { + let wide = show_in(open, vec2(1600.0, 1000.0), false); + let Some((right, _)) = texts(&wide) + .into_iter() + .filter(|(_, r, _)| wide.window.contains_rect(*r)) + .map(|(s, r, _)| (s, r.right())) + .max_by(|a, b| a.1.total_cmp(&b.1)) + else { + wrong.push(format!("{name}: no text in the large window")); + continue; + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0)); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + // Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge. + let seen = + |shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r)); + let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width()); + if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) { + let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::>(); + wrong.push(format!( + "{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}", + screen.size(), + shown.window, + shown.whole, + seen(&shown), + at(&shown), + seen(&scrolled), + at(&scrolled), + bars(&shown, true, true) + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Every text the dialog drew, with its rectangle and its clip. +fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> { + fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out)); + out +} + +#[test] +fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() { + // Check Spelling draws its buttons inside its body: in a window too short for it, the heading + // stays in view and the buttons scroll with the body. + let open: Open = |app| { + check_spelling::open(app).unwrap(); + }; + let tall = show_in(open, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round())); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole); + assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view"); + assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down"); +} diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 6cffc344d1..0ee21574fb 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -4,10 +4,13 @@ //! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find //! to the active artboard or the selected layers. +use std::sync::Arc; + use egui::Ui; use serde_json::{Value, json}; use crate::VectorcraftApp; +use crate::caches::{FindFontCache, FontsKey}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -20,7 +23,7 @@ pub fn open(app: &mut VectorcraftApp) { /// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find /// Fonts). pub fn open_on_missing(app: &mut VectorcraftApp) { - let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); + let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); open_at(app, first.unwrap_or(0)); } @@ -28,7 +31,7 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { /// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first). fn open_at(app: &mut VectorcraftApp, selected: usize) { let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document"); - let used = fonts(app); + let (used, _) = document_fonts(app, false); let source = "system"; let rows = replacement_rows(app, source, &used); let family = system_family(); @@ -252,6 +255,30 @@ fn fonts(app: &mut VectorcraftApp) -> Vec { app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default() } +/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a +/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked +/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another +/// document, another version of its content or another font generation. No document: no fonts. +fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc>, bool) { + let Some(st) = app.session.active() else { return (Arc::default(), false) }; + // The generation is read first: fonts loaded while the answers are worked out leave the entry + // under the older generation, so the next frame works them out again. + let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() }; + if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) { + let fonts = Arc::new(fonts(app)); + app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None }); + } + if missing + && let Some(c) = app.canvas.find_font.as_mut() + && c.missing.is_none() + && let Some(st) = app.session.active() + { + c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + } + let c = app.canvas.find_font.as_ref(); + (c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false)) +} + pub fn confirm(app: &mut VectorcraftApp) -> Result { if let Some(ctx) = app.ui_ctx.clone() { clear_search(&ctx); @@ -279,10 +306,9 @@ fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Resu pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); - let list = fonts(app); // Find in Folder… shows when the document misses fonts, fonts used only in its symbols included. - let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder) - && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder); + let (list, offer_folder) = document_fonts(app, can_pick); let mut close = false; let mut find_in_folder = false; let mut act: Option<&str> = None; @@ -416,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { match run_button(app, &d, a, from) { // The rows are a snapshot: the document's fonts and the recent fonts have moved on. Ok(_) if a != "find" => { - let used = fonts(app); + let (used, _) = document_fonts(app, false); d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used))); } Ok(_) => {} @@ -1421,4 +1447,231 @@ mod tests { let (note, color) = font_note(&row("exact", 2)); assert!(note.contains("2 characters") && color.is_some()); } + + /// The font list the dialog keeps for the active document. + fn kept_list(app: &VectorcraftApp) -> Arc> { + app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone() + } + + /// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now. + fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) { + let listed = fonts(app); + assert_eq!(*kept_list(app), listed, "{why}: the list"); + let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder); + assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}"); + } + + /// A document set in a missing family and in Inter, with a folder picker. + fn missing_font_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Missing Family"), (40, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + app + } + + /// Frames that change nothing in the document, a new selection included, keep the font list + /// and the missing-font answer worked out on the first; the answer is worked out only once a + /// folder picker is there. + #[test] + fn the_font_list_is_worked_out_once_per_document_version() { + let mut app = missing_font_document(); + let picker = app.services.pick_folder.take(); + open(&mut app); + assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts"); + app.services.pick_folder = picker; + assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true)); + app.run("select.all", json!({})).unwrap(); + assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list"); + } + + /// Draws frames of the dialog and tells whether they kept the list kept before them. Another + /// test thread that changes the available fonts meanwhile makes the dialog work the list out + /// again, so the frames are drawn again until the fonts stay as they are. + fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool { + for _ in 0..20 { + // The generation the kept list was worked out under: the database's generation only + // counts up, so the same one after the frames means no fonts changed in between. + let before = kept_list(app); + let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation); + let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + assert_current(app, &shown, why); + if Some(vectorcraft_text::FontDb::global().generation()) == generation { + return Arc::ptr_eq(&before, &kept_list(app)); + } + } + panic!("{why}: the available fonts kept changing") + } + + /// An edit, its undo and a Change All each give the list of the document as it is then. + #[test] + fn an_edit_works_the_font_list_out_again() { + let mut app = missing_font_document(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + let first = kept_list(&app); + app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the replacement"); + assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}"); + assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app)); + app.run("edit.undo", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the undo"); + assert_eq!(*kept_list(&app), *first, "the undo brings back the first list"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Serif 4")); + d.fields.insert("style".into(), json!("")); + let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after Change All"); + assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app)); + } + + /// Fonts that become available, a composite font defined among them, give the list and the + /// missing-font answer as they are with those fonts. + #[test] + fn other_available_fonts_work_the_font_list_out_again() { + const FAMILY: &str = "Find Font Kept List CF"; + let mut app = missing_font_document(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + // The same document under another generation of the font database: what is kept for it no + // longer counts. + let entry = app.canvas.find_font.as_mut().unwrap(); + entry.key.generation = u64::MAX; + entry.fonts = Arc::default(); + entry.missing = Some(false); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "another font generation"); + let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap(); + assert_eq!(row(&app)["status"], "missing"); + let generation = vectorcraft_text::FontDb::global().generation(); + let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}}); + app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap(); + assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font defined"); + assert_eq!(row(&app)["status"], "exact"); + app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font taken out"); + assert_eq!(row(&app)["status"], "missing"); + } + + /// Another document in front, and pattern editing entered and canceled, each give the list of + /// the document in front as it is then. + #[test] + fn the_font_list_follows_the_document_in_front() { + let mut app = missing_font_document(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone(); + app.services.pick_folder = Some(Box::new(|| None)); + open(&mut app); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the second document"); + app.session.set_active(0); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the first document"); + assert!(shown.contains("Find in Folder…"), "{shown}"); + app.session.set_active(1); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap(); + assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing"); + app.run("object.pattern.cancel", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing canceled"); + } + + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + + /// Time the font list and the missing-font answer a Find Font frame reads, for a document of + /// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces + /// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and + /// `missing_fonts` (each frame before they were kept), on the first frame of a document version + /// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document + /// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in + /// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides + /// alternate, and the median time per frame of 7 runs is printed. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn find_font_list_timing() { + const KEPT: u32 = 1_000_000; + const FACES: [(&str, &str); 6] = [ + ("Inter", "Regular"), + ("Inter", "Medium"), + ("Source Sans 3", "Bold"), + ("Source Serif 4", "Regular"), + ("JetBrains Mono", "Regular"), + ("Missing Family", "Regular"), + ]; + for (objects, frames) in [(2_000, 120), (20, 12_000)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); + for i in 0..objects { + let (family, style) = FACES[i % FACES.len()]; + let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect(); + let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0); + app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + let every_frame = |app: &mut VectorcraftApp| { + let list = fonts(app); + let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder) + && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + (list, offer) + }; + let expected = every_frame(&mut app); + assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}"); + let kept = document_fonts(&mut app, true); + assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame"); + // Each side's answers for one frame: the number of fonts listed and Find in Folder…. + let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..frames { + assert_eq!(f(app), (FACES.len(), true)); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(frames) / 1000.0 + }; + let (mut full, mut first, mut later) = (vec![], vec![], vec![]); + for _ in 0..7 { + full.push(time(&mut app, frames, &mut |app| { + let (list, offer) = every_frame(app); + (list.len(), offer) + })); + first.push(time(&mut app, frames, &mut |app| { + app.canvas.find_font = None; + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + later.push(time(&mut app, KEPT, &mut |app| { + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs"); + eprintln!("worked out every frame ({frames} frames a run): {:>12.3} us {full:.3?}", median(&mut full)); + eprintln!("first frame of a version ({frames} a run): {:>12.3} us {first:.3?}", median(&mut first)); + eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us {later:.4?}", median(&mut later)); + } + } } diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index d6c5e0d071..855bc3a3f4 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -518,10 +518,10 @@ impl Filters { /// The families the type in `doc` is set in, lowercase and by the name the menu lists them under /// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols, -/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named -/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked -/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find -/// the installed font of that name. Styles no type uses are left out. +/// patterns, graph designs and stored scatter brushes, hidden, locked and masked ones included, with +/// a composite font named as such. A pattern being edited is read from its editing layer only. Each +/// run's family is looked up with its style, so a family and style split from a PostScript name +/// (`Honoka`, `Mincho`) find the installed font of that name. Styles no type uses are left out. fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet { // Each family and style once, so a document with many runs in a few fonts looks each one up // once. @@ -549,6 +549,14 @@ fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Docum for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) { vectorcraft_doc::swatches::walk_with_masks(n, &mut add); } + // A scatter brush draws copies of its art's type along a stroke; art and pattern brushes drop + // type when they bend their art. Malformed library entries are skipped. + let brushes = doc.unknown.get(vectorcraft_brush::DOC_KEY).map(vectorcraft_brush::parse_library).unwrap_or_default(); + for b in &brushes { + if let vectorcraft_brush::BrushKind::Scatter(s) = &b.kind { + vectorcraft_doc::swatches::walk_with_masks(&s.art, &mut add); + } + } named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect() } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 7cf20d4210..7d930b7af5 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1221,6 +1221,58 @@ fn the_document_filter_counts_type_in_graph_designs() { assert_eq!(names, ["inter", "jetbrains mono"]); } +/// Type in the art of a stored scatter brush counts as the document's type, as a scatter stroke +/// draws it, after a malformed library entry too. Type in an art or pattern brush's art does not, +/// as those brushes leave type out when they bend their art. +#[test] +fn the_document_filter_counts_type_in_scatter_brushes() { + let mut app = app_with_type(&["Inter"]); + let mut art = |font: &str| { + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": font})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + node + }; + let (scatter, bent, tiled) = (art("JetBrains Mono"), art("Source Serif 4"), art("Source Sans 3")); + let brush = |name: &str, kind| serde_json::to_value(vectorcraft_brush::Brush { name: name.into(), kind }).unwrap(); + let library = serde_json::json!([ + {"name": "Broken", "type": "scatter", "art": 7}, + brush("Art", vectorcraft_brush::BrushKind::Art(vectorcraft_brush::ArtBrush { art: bent, ..Default::default() })), + brush("Pattern", vectorcraft_brush::BrushKind::Pattern(vectorcraft_brush::PatternBrush { side: tiled, ..Default::default() })), + brush("Dots", vectorcraft_brush::BrushKind::Scatter(vectorcraft_brush::Scatter { art: scatter, ..Default::default() })), + ]); + let mut doc = (*app.session.active().unwrap().doc).clone(); + doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), library); + let db = vectorcraft_text::FontDb::global(); + let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect(); + names.sort(); + assert_eq!(names, ["inter", "jetbrains mono"]); +} + +/// A scatter brush made of type keeps its family in the Document filter after the type is deleted; +/// deleting the brush takes the family out, and undoing the deletion brings it back. +#[test] +fn the_document_filter_follows_a_scatter_brushs_edits_and_undo() { + let mut app = app_with_type(&["Inter"]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": "JetBrains Mono"})).unwrap()["id"].clone(); + let name = app.run("brush.new", serde_json::json!({"type": "scatter", "name": "Type Dots"})).unwrap()["name"].clone(); + app.run("edit.clear", serde_json::json!({"ids": [id]})).unwrap(); + let db = vectorcraft_text::FontDb::global(); + // One menu state throughout, so each edit has to get past the families it keeps. + let mut st = super::MenuState { document_only: true, ..Default::default() }; + let mut families = |app: &crate::VectorcraftApp| { + let used = super::used_families(db, &mut st, super::MenuLook::of(app)).expect("a document is open"); + let mut names: Vec<_> = used.iter().cloned().collect(); + names.sort(); + names + }; + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the brush's type"); + app.run("brush.delete", serde_json::json!({"name": name})).unwrap(); + assert_eq!(families(&app), ["inter"], "the brush deleted"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the deletion undone"); +} + /// A run whose family and style were split from a PostScript name (as an importer without the font /// splits one) counts under the family of the installed font of that name, found with its style. #[test] diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index df5d05fc95..e43e4bf0f4 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -640,6 +640,11 @@ pub fn tr_ctx<'a>(lang: Lang, context: &str, s: &'a str) -> &'a str { lang.catalog().contextual(context, s).unwrap_or_else(|| tr(lang, s)) } +/// The translation of `s` in `lang`'s `context` rows alone, or `None` when it has no such row. +pub fn tr_ctx_row(lang: Lang, context: &str, s: &str) -> Option<&'static str> { + lang.catalog().contextual(context, s) +} + /// A name the app gives something (a default swatch's), translated where the current language has /// a `context` row for it; any other name (one the user gave) comes back as it is. pub fn t_name<'a>(context: &str, name: &'a str) -> &'a str { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8d833f9cdb..056fbd715b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -127,6 +127,7 @@ Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове Additional Plug-ins Folder Допълнителна папка за плъгини + Plug-in Instruction Budget Бюджет на инструкции за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина Incoming Входяща @@ -792,6 +793,7 @@ font-technology Variable Променливи Delete Brush Изтриване на четка Delete Color Изтриване на цвят Restore Generated Table Възстановяване на генерираната таблица + Unshift All Colors Преместване назад на всички цветове Delete Character Style Изтриване на стил за знаци Delete Empty Artboards Изтриване на празни работни области Delete Freeform Point Изтриване на свободна точка @@ -3141,6 +3143,8 @@ digits Malayalam Малаялам How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Колко близо на екрана показалецът или влачена точка трябва да стигне до обект, за да прилепнат интелигентните водачи; разстоянието е еднакво при всеки мащаб. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Прилепва края на линеен сегмент или окръжност, начертана от центъра си, така че да докосва близка крива. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Прилепва края на линеен сегмент така, че да среща близък прав сегмент под прав ъгъл. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показва номера на всяка отрязана част в каре в горния ѝ ляв ъгъл върху платното; когато е изключено, контурите на отрязаните части остават видими. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Цветът на контурите на потребителските и обектните отрязани части и на каретата с номерата им; автоматичните отрязани части използват по-блед нюанс на този цвят. Reset all preferences to their defaults? Да се нулират ли всички настройки до стойностите по подразбиране? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Стойностите по подразбиране се прилагат, когато щракнете върху ОК в Настройки. Отказ там запазва текущите ви настройки. Restore Recovered Documents Възстановяване на възстановените документи @@ -3358,6 +3362,12 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти… No commands match Няма съвпадащи команди {pos} of {total}: {name} {pos} от {total}: {name} + No menu item Няма елемент в менюто + Toolbar Лента с инструменти + {toolbar}, in the {tool} group {toolbar}, в групата на {tool} + In the menu bar: {path} В лентата с менюта: {path} + In the {group} group: press and hold to open it В групата {group}: натиснете и задръжте, за да я отворите + {home}, not shown now {home}, не се показва сега @plural {n} result|{n} results {n} резултат|{n} резултата @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните. Recent Commands Последни команди @@ -4677,6 +4687,7 @@ axis Both И двете @msg choose a location for the package изберете местоположение за пакета @msg clipboard is empty клипбордът е празен @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: поне един цвят трябва да остане в цветовата таблица +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` назовава цвят, който друг ключ също назовава @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не е цвят като "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: най-много {MAX_TABLE} цвята @msg command `{0}` is not available right now: {1} команда `{0}` не е налична в момента: {1} @@ -7024,6 +7035,7 @@ breakText Glyphs Глифи @msg One path lies inside the other, so they have no common tangents Единият път е вътре в другия, затова нямат общи допирателни @msg The paths overlap, so they have no internal tangents Пътищата се припокриват, затова нямат вътрешни допирателни @msg One path lies inside the other, so they have no internal tangents Единият път е вътре в другия, затова нямат вътрешни допирателни +@msg The point lies inside the path, so it has no tangents Точката е вътре в пътя, затова няма допирателни # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разширяване на тиретата в пътища @msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване @@ -7366,3 +7378,8 @@ breakText Glyphs Глифи @msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. @msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Pressure Sensitive Чувствителни на натиск + Flex Ribbon Гъвкава лента + Pulse Stroke Пулсиращ щрих + Round Flow Кръгъл поток + Chisel Flow Скосен поток diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 280056bb88..e6c0ccce78 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3488,6 +3488,7 @@ theme Appearance Izgled Delete Brush Izbriši četkicu Delete Color Izbriši boju Restore Generated Table Vrati generisanu tabelu + Unshift All Colors Poništi pomak svih boja Delete Symbol Izbriši simbol Delete the selected symbol? Izbrisati odabrani simbol? Delete the selected symbols? Izbrisati odabrane simbole? @@ -3944,6 +3945,7 @@ theme Appearance Izgled 90° & 45° Angles Uglovi od 90° i 45° 90° Angles Uglovi od 90° Additional Plug-ins Folder Dodatni folder dodataka + Plug-in Instruction Budget Budžet instrukcija za dodatke Additional Fonts Folder Dodatni folder fontova Alignment Guides Vodilice za poravnanje Anchor Points, Handle, and Bounding Box Display Prikaz sidrenih tačaka, ručki i graničnog okvira @@ -4479,6 +4481,12 @@ font-technology Variable Varijabilni Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte… No commands match Nijedna naredba se ne podudara {pos} of {total}: {name} {pos} od {total}: {name} + No menu item Nema stavke menija + Toolbar Traka s alatima + {toolbar}, in the {tool} group {toolbar}, u grupi {tool} + In the menu bar: {path} Na traci menija: {path} + In the {group} group: press and hold to open it U grupi {group}: pritisnite i držite da je otvorite + {home}, not shown now {home}, trenutno nije prikazano @plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite. Recent Commands Nedavne naredbe @@ -4596,6 +4604,8 @@ font-technology Variable Varijabilni How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Koliko blizu na ekranu pokazivač ili prevučena tačka mora doći do objekta da bi ga pametne vodilice uhvatile; udaljenost je ista pri svakom zumu. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Hvata kraj segmenta linije ili krug nacrtan iz središta tako da dodiruje obližnju krivu. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Hvata kraj segmenta linije tako da pod pravim uglom susreće obližnji ravni segment. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Prikazuje broj svakog isječka u okviru u njegovom gornjem lijevom uglu na platnu; kada je isključeno, obrisi isječaka i dalje se prikazuju. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Boja obrisa korisničkih i objektnih isječaka i okvira s njihovim brojevima; automatski isječci koriste blijeđu nijansu te boje. Reset all preferences to their defaults? Vratiti sve postavke na zadane vrijednosti? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Zadane vrijednosti primjenjuju se kada kliknete U redu u Postavkama. Otkaži tamo zadržava vaše trenutne postavke. Smaller ↔ Larger Manje ↔ veće @@ -5085,6 +5095,7 @@ imageTrace Outline Obris @msg choose a location for the package odaberite lokaciju za paket @msg clipboard is empty međuspremnik je prazan @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: barem jedna boja mora ostati u tabeli boja +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` imenuje boju koju imenuje i drugi ključ @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nije boja poput "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: najviše {MAX_TABLE} boja @msg command `{0}` is not available right now: {1} naredba `{0}` trenutno nije dostupna: {1} @@ -7073,6 +7084,7 @@ shape Open Otvoren @msg One path lies inside the other, so they have no common tangents Jedna putanja leži unutar druge, pa nemaju zajedničkih tangenti @msg The paths overlap, so they have no internal tangents Putanje se preklapaju, pa nemaju unutrašnjih tangenti @msg One path lies inside the other, so they have no internal tangents Jedna putanja leži unutar druge, pa nemaju unutrašnjih tangenti +@msg The point lies inside the path, so it has no tangents Tačka leži unutar putanje, pa nema tangenti # 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 @@ -7421,3 +7433,8 @@ shape Open Otvoren @msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. @msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Pressure Sensitive Osjetljivo na pritisak + Flex Ribbon Savijajuća traka + Pulse Stroke Pulsirajući potez + Round Flow Okrugli tok + Chisel Flow Kosi tok diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5d0db6ef1d..77183ad8c7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -223,6 +223,7 @@ Add Used Colors Afegeix els colors utilitzats Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements + Plug-in Instruction Budget Pressupost d’instruccions dels complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus Incoming Entrant Outgoing Sortint @@ -1155,6 +1156,7 @@ antiAlias Sharp Nítid Delete Brush Suprimeix el pinzell Delete Color Suprimeix el color Restore Generated Table Restaura la taula generada + Unshift All Colors Desfés el desplaçament de tots els colors Delete Character Style Suprimeix l’estil de caràcter Delete Data Set Suprimeix el conjunt de dades Delete Data Sets Suprimeix els conjunts de dades @@ -3983,6 +3985,8 @@ digits Malayalam Malaiàlam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Com d’a prop a la pantalla han d’arribar el punter o un punt arrossegat a l’art perquè les guies intel·ligents s’hi ajustin; la distància és la mateixa a qualsevol zoom. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Ajusta l’extrem d’un segment de línia, o un cercle dibuixat des del centre, perquè toqui una corba propera. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Ajusta l’extrem d’un segment de línia perquè trobi un segment recte proper en angle recte. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra al llenç el número de cada tall en un requadre a la seva cantonada superior esquerra; si està desactivat, els contorns dels talls continuen visibles. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. El color dels contorns dels talls d’usuari i d’objecte i dels requadres amb el seu número; els talls automàtics fan servir un to més apagat d’aquest color. Reset all preferences to their defaults? Voleu restablir totes les preferències als valors predeterminats? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Els valors predeterminats s’apliquen quan feu clic a D’acord a Preferències. Cancel·la allà conserva les preferències actuals. Restore Recovered Documents Restaura els documents recuperats @@ -4301,6 +4305,12 @@ digits Malayalam Malaiàlam Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes… No commands match Cap ordre coincideix {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Cap element de menú + Toolbar Barra d’eines + {toolbar}, in the {tool} group {toolbar}, al grup {tool} + In the menu bar: {path} A la barra de menús: {path} + In the {group} group: press and hold to open it Al grup {group}: manteniu premut per obrir-lo + {home}, not shown now {home}, ara no es mostra @plural {n} result|{n} results {n} resultat|{n} resultats @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los. Recent Commands Ordres recents @@ -5804,6 +5814,7 @@ digits Malayalam Malaiàlam @msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura @msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura @msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura +@msg a linked file's editing data can't be read to check it against the read roots no es poden llegir les dades d’edició d’un fitxer enllaçat per comprovar-les amb les arrels de lectura @msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura @msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat @msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path} @@ -5858,6 +5869,7 @@ digits Malayalam Malaiàlam @msg clipboard is empty el porta-retalls és buit @msg closing needs three anchors el tancament necessita tres punts d’ancoratge @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: almenys un color ha de quedar a la taula de colors +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` indica un color que també indica una altra clau @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` no és un color com "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: com a màxim {MAX_TABLE} colors @msg column docks a set as a dock column, with no anchor or icon column acobla un conjunt com a columna d’acoblament, sense àncora ni icona @@ -7812,6 +7824,7 @@ breakText Glyphs Glifs @msg One path lies inside the other, so they have no common tangents Un camí és dins de l’altre, per tant no tenen tangents comunes @msg The paths overlap, so they have no internal tangents Els camins se superposen, per tant no tenen tangents internes @msg One path lies inside the other, so they have no internal tangents Un camí és dins de l’altre, per tant no tenen tangents internes +@msg The point lies inside the path, so it has no tangents El punt és dins del camí, per tant no té tangents # 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 @@ -8318,4 +8331,9 @@ breakText Glyphs Glifs @msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. @msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Pressure Sensitive Sensible a la pressió + Flex Ribbon Cinta flexible + Pulse Stroke Traç pulsant + Round Flow Flux rodó + Chisel Flow Flux bisellat @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: utilitzeu "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3076fe7875..869e47483f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3588,6 +3588,7 @@ theme Appearance Motiv Delete Brush Odstranit štětec Delete Color Odstranit barvu Restore Generated Table Obnovit vygenerovanou tabulku + Unshift All Colors Zrušit posun všech barev Delete Symbol Odstranit symbol Delete the selected symbol? Odstranit vybraný symbol? Delete the selected symbols? Odstranit vybrané symboly? @@ -4048,6 +4049,7 @@ theme Appearance Motiv 90° & 45° Angles Úhly 90° a 45° 90° Angles Úhly 90° Additional Plug-ins Folder Další složka zásuvných modulů + Plug-in Instruction Budget Rozpočet instrukcí zásuvných modulů Additional Fonts Folder Další složka písem Alignment Guides Vodítka zarovnání Anchor Points, Handle, and Bounding Box Display Zobrazení kotevních bodů, úchytů a ohraničovacího rámečku @@ -4587,6 +4589,12 @@ font-technology Variable Variabilní Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty… No commands match Žádný příkaz neodpovídá {pos} of {total}: {name} {pos} z {total}: {name} + No menu item Žádná položka nabídky + Toolbar Panel nástrojů + {toolbar}, in the {tool} group {toolbar}, ve skupině {tool} + In the menu bar: {path} V řádku nabídek: {path} + In the {group} group: press and hold to open it Ve skupině {group}: stisknutím a podržením ji otevřete + {home}, not shown now {home}, nyní není zobrazeno @plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží. Recent Commands Nedávné příkazy @@ -4704,6 +4712,8 @@ font-technology Variable Variabilní How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blízko na obrazovce musí ukazatel nebo tažený bod přijít ke kresbě, aby se chytrá vodítka přichytila; vzdálenost je stejná při každém zvětšení. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Přichytí konec úsečky nebo kružnici kreslenou od středu tak, aby se dotýkala blízké křivky. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Přichytí konec úsečky tak, aby se s blízkým rovným segmentem setkal v pravém úhlu. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Zobrazí na plátně číslo každého řezu v rámečku v jeho levém horním rohu; když je vypnuto, obrysy řezů zůstanou zobrazené. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Barva obrysů uživatelských a objektových řezů a rámečků s jejich čísly; automatické řezy používají tlumenější odstín této barvy. Reset all preferences to their defaults? Obnovit všechny předvolby na výchozí hodnoty? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Výchozí hodnoty se použijí po klepnutí na OK v Předvolbách. Zrušit tam zachová vaše současné předvolby. Smaller ↔ Larger Menší ↔ Větší @@ -5380,6 +5390,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg choose a location for the package zvolte umístění balíčku @msg clipboard is empty schránka je prázdná @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: v tabulce barev musí zůstat alespoň jedna barva +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` označuje barvu, kterou označuje i jiný klíč @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` není barva jako "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: nejvýše {MAX_TABLE} barev @msg command `{0}` is not available right now: {1} příkaz `{0}` nyní není k dispozici: {1} @@ -6016,6 +6027,7 @@ variable-list-end {0}, {1} {0} a {1} @msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení @msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení @msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení +@msg a linked file's editing data can't be read to check it against the read roots editační data propojeného souboru nelze přečíst a ověřit vůči kořenům pro čtení @msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path} @msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná @@ -7797,6 +7809,7 @@ breakText Glyphs Glyfy @msg One path lies inside the other, so they have no common tangents Jedna cesta leží uvnitř druhé, takže nemají žádné společné tečny @msg The paths overlap, so they have no internal tangents Cesty se překrývají, takže nemají žádné vnitřní tečny @msg One path lies inside the other, so they have no internal tangents Jedna cesta leží uvnitř druhé, takže nemají žádné vnitřní tečny +@msg The point lies inside the path, so it has no tangents Bod leží uvnitř cesty, takže nemá žádné tečny # 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í @@ -10103,6 +10116,11 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Pressure Sensitive Citlivé na tlak + Flex Ribbon Pružná stuha + Pulse Stroke Pulzující tah + Round Flow Kulatý tah + Chisel Flow Zkosený tah Fold Preview Náhled skládání Fold Složení Show Fold Lines Zobrazit linie skladu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b610b9116d..a2966f09f1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1439,6 +1439,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne @msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne @msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdataene for en linket fil kan ikke læses for at kontrollere dem mod læserødderne @msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt @msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI @msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret @@ -6043,6 +6044,7 @@ theme Appearance Udseende Delete Brush Slet pensel Delete Color Slet farve Restore Generated Table Gendan genereret tabel + Unshift All Colors Fjern skift af alle farver Delete Symbol Slet symbol Delete the selected symbol? Vil du slette det markerede symbol? Delete the selected symbols? Vil du slette de markerede symboler? @@ -6496,6 +6498,7 @@ theme Appearance Udseende 90° & 45° Angles 90° & 45°-vinkler 90° Angles 90°-vinkler Additional Plug-ins Folder Yderligere mappe med plug-ins + Plug-in Instruction Budget Instruktionsbudget for plug-ins Additional Fonts Folder Yderligere mappe med skrifttyper Alignment Guides Justeringshjælpelinjer Anchor Points, Handle, and Bounding Box Display Visning af ankerpunkter, håndtag og afgrænsningsboks @@ -7010,6 +7013,12 @@ font-technology Variable Variable Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter… No commands match Ingen kommandoer passer {pos} of {total}: {name} {pos} af {total}: {name} + No menu item Intet menupunkt + Toolbar Værktøjslinje + {toolbar}, in the {tool} group {toolbar}, i gruppen {tool} + In the menu bar: {path} I menulinjen: {path} + In the {group} group: press and hold to open it I gruppen {group}: tryk og hold for at åbne den + {home}, not shown now {home}, vises ikke nu @plural {n} result|{n} results {n} resultat|{n} resultater @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem. Recent Commands Seneste kommandoer @@ -7127,6 +7136,8 @@ font-technology Variable Variable How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Hvor tæt på skærmen markøren eller et trukket punkt skal komme på grafik, for at de smarte hjælpelinjer fastgør til den; afstanden er den samme ved alle zoomniveauer. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Fastgør enden af et linjesegment eller en cirkel tegnet fra midten, så den rører en nærliggende kurve. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Fastgør enden af et linjesegment, så det møder et nærliggende lige segment i en ret vinkel. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Viser hvert udsnits nummer i en boks i dets øverste venstre hjørne på lærredet; når den er slået fra, vises udsnittenes konturer stadig. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Farven på konturerne af bruger- og objektudsnit og på boksene med deres numre; automatiske udsnit bruger en svagere nuance af den. Reset all preferences to their defaults? Nulstil alle præferencer til standard? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardværdierne anvendes, når du klikker på OK i Præferencer. Annullér der beholder dine nuværende præferencer. Smaller ↔ Larger Mindre ↔ Større @@ -7573,6 +7584,7 @@ imageTrace Outline Kontur @msg choose a location for the package vælg en placering til pakken @msg clipboard is empty udklipsholderen er tom @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: mindst én farve skal blive i farvetabellen +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` angiver en farve, som en anden nøgle også angiver @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` er ikke en farve som "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: højst {MAX_TABLE} farver @msg command `{0}` is not available right now: {1} kommandoen `{0}` er ikke tilgængelig lige nu: {1} @@ -9851,6 +9863,7 @@ breakText Glyphs Glyffer @msg One path lies inside the other, so they have no common tangents Den ene sti ligger inden i den anden, så de har ingen fælles tangenter @msg The paths overlap, so they have no internal tangents Stierne overlapper, så de har ingen indre tangenter @msg One path lies inside the other, so they have no internal tangents Den ene sti ligger inden i den anden, så de har ingen indre tangenter +@msg The point lies inside the path, so it has no tangents Punktet ligger inden i stien, så det har ingen tangenter # 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 @@ -10206,3 +10219,8 @@ breakText Glyphs Glyffer @msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. @msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Pressure Sensitive Trykfølsom + Flex Ribbon Fleksibelt bånd + Pulse Stroke Pulserende strøg + Round Flow Rundt strøg + Chisel Flow Skråt strøg diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9f0b61afac..bef5d6b62f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -116,6 +116,7 @@ Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner + Plug-in Instruction Budget Anweisungsbudget für Plug-ins Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen Incoming Eingehend @@ -799,6 +800,7 @@ font-technology Variable Variabel Delete Brush Pinsel löschen Delete Color Farbe löschen Restore Generated Table Generierte Tabelle wiederherstellen + Unshift All Colors Verschiebung aller Farben aufheben Delete Character Style Zeichenformat löschen Delete Empty Artboards Leere Zeichenflächen löschen Delete Freeform Point Freiformpunkt löschen @@ -3205,6 +3207,8 @@ digits Malayalam Malayalam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Wie nah der Zeiger oder ein gezogener Punkt auf dem Bildschirm an Bildmaterial kommen muss, damit intelligente Hilfslinien einrasten; der Abstand ist bei jedem Zoom gleich. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Richtet das Ende eines Liniensegments oder einen von der Mitte aus gezeichneten Kreis so aus, dass er eine nahe Kurve berührt. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Richtet das Ende eines Liniensegments so aus, dass es ein nahes gerades Segment im rechten Winkel trifft. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Zeigt auf der Arbeitsfläche die Nummer jedes Slices in einem Kästchen oben links im Slice; ist die Option aus, werden die Slice-Umrisse weiterhin angezeigt. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Die Farbe der Umrisse von Benutzer- und Objekt-Slices und ihrer Nummernkästchen; automatische Slices verwenden einen blasseren Ton davon. Reset all preferences to their defaults? Alle Voreinstellungen auf ihre Standardwerte zurücksetzen? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Die Standardwerte werden angewendet, wenn Sie in den Voreinstellungen auf OK klicken. Abbrechen dort behält Ihre aktuellen Voreinstellungen. Restore Recovered Documents Wiederhergestellte Dokumente öffnen @@ -3436,6 +3440,14 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen… No commands match Keine passenden Befehle {pos} of {total}: {name} {pos} von {total}: {name} + No menu item Kein Menüeintrag + Toolbar Werkzeugleiste + {toolbar}, in the {tool} group {toolbar}, in der Gruppe „{tool}“ + In the menu bar: {path} In der Menüleiste: {path} + In the {group} group: press and hold to open it In der Gruppe {group}: zum Öffnen gedrückt halten + {home}, not shown now {home}, derzeit nicht angezeigt + Tool Werkzeug + Command Befehl @plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen. Recent Commands Zuletzt verwendete Befehle @@ -4973,6 +4985,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg choose a location for the package wählen Sie einen Speicherort für das Paket @msg clipboard is empty die Zwischenablage ist leer @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: Mindestens eine Farbe muss in der Farbtabelle bleiben +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` bezeichnet eine Farbe, die auch ein anderer Schlüssel bezeichnet @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ist keine Farbe wie "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: höchstens {MAX_TABLE} Farben @msg command `{0}` is not available right now: {1} der Befehl `{0}` ist derzeit nicht verfügbar: {1} @@ -7384,6 +7397,7 @@ breakText Glyphs Glyphen @msg One path lies inside the other, so they have no common tangents Ein Pfad liegt im anderen, daher haben sie keine gemeinsamen Tangenten @msg The paths overlap, so they have no internal tangents Die Pfade überlappen sich, daher haben sie keine inneren Tangenten @msg One path lies inside the other, so they have no internal tangents Ein Pfad liegt im anderen, daher haben sie keine inneren Tangenten +@msg The point lies inside the path, so it has no tangents Der Punkt liegt im Pfad, daher hat er keine Tangenten # 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 @@ -9581,6 +9595,7 @@ breakText Glyphs Glyphen @msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner @msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner @msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner +@msg a linked file's editing data can't be read to check it against the read roots die Bearbeitungsdaten einer verknüpften Datei können nicht gelesen werden, um sie mit den Lesestammordnern abzugleichen @msg a number cannot be read eine Zahl kann nicht gelesen werden @msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang @msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang @@ -9705,6 +9720,11 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Pressure Sensitive Druckempfindlich + Flex Ribbon Flexibles Band + Pulse Stroke Pulsierender Strich + Round Flow Runder Fluss + Chisel Flow Schräger Fluss Fold Preview Faltvorschau Fold Falten Show Fold Lines Faltlinien einblenden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a15c2c555f..cf4ef52e41 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -121,6 +121,7 @@ Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων + Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους Incoming Εισερχόμενο @@ -777,6 +778,7 @@ font-technology Variable Μεταβλητές Delete Brush Διαγραφή πινέλου Delete Color Διαγραφή χρώματος Restore Generated Table Επαναφορά του παραγόμενου πίνακα + Unshift All Colors Αναίρεση μετατόπισης όλων των χρωμάτων Delete Character Style Διαγραφή στυλ χαρακτήρων Delete Empty Artboards Διαγραφή κενών πινάκων σχεδίασης Delete Freeform Point Διαγραφή ελεύθερου σημείου @@ -4060,6 +4062,8 @@ digits Malayalam Μαλαγιάλαμ How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Πόσο κοντά στην οθόνη πρέπει να φτάσει ο δείκτης ή ένα σημείο που σύρεται σε γραφικά για να προσκολληθούν οι έξυπνοι οδηγοί· η απόσταση είναι ίδια σε κάθε ζουμ. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Προσκολλά το άκρο ενός ευθύγραμμου τμήματος ή έναν κύκλο που σχεδιάζεται από το κέντρο του ώστε να αγγίζει μια κοντινή καμπύλη. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Προσκολλά το άκρο ενός ευθύγραμμου τμήματος ώστε να συναντά ένα κοντινό ευθύ τμήμα σε ορθή γωνία. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Εμφανίζει στον καμβά τον αριθμό κάθε τομής σε ένα πλαίσιο πάνω αριστερά της· όταν είναι απενεργοποιημένο, τα περιγράμματα των τομών εξακολουθούν να εμφανίζονται. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Το χρώμα των περιγραμμάτων των τομών χρήστη και αντικειμένου και των πλαισίων με τους αριθμούς τους· οι αυτόματες τομές χρησιμοποιούν μια πιο αχνή απόχρωσή του. Reset all preferences to their defaults? Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους; The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Οι προεπιλογές εφαρμόζονται όταν κάνετε κλικ στο Εντάξει στις Προτιμήσεις. Το Ακύρωση εκεί διατηρεί τις τρέχουσες προτιμήσεις σας. Restore Recovered Documents Επαναφορά ανακτημένων εγγράφων @@ -4177,6 +4181,12 @@ digits Malayalam Μαλαγιάλαμ Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ… No commands match Καμία εντολή δεν ταιριάζει {pos} of {total}: {name} {pos} από {total}: {name} + No menu item Χωρίς στοιχείο μενού + Toolbar Γραμμή εργαλείων + {toolbar}, in the {tool} group {toolbar}, στην ομάδα {tool} + In the menu bar: {path} Στη γραμμή μενού: {path} + In the {group} group: press and hold to open it Στην ομάδα {group}: πατήστε παρατεταμένα για να ανοίξει + {home}, not shown now {home}, δεν εμφανίζεται τώρα @plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε. Recent Commands Πρόσφατες εντολές @@ -5037,6 +5047,7 @@ digits Malayalam Μαλαγιάλαμ @msg choose a location for the package επιλέξτε τοποθεσία συσκευασίας @msg clipboard is empty το πρόχειρο είναι κενό @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: τουλάχιστον ένα χρώμα πρέπει να παραμείνει στον πίνακα χρωμάτων +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: το `{k}` ορίζει ένα χρώμα που ορίζει και άλλο κλειδί @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: το `{h}` δεν είναι έγκυρο χρώμα, όπως το "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: επιτρέπονται το πολύ {MAX_TABLE} χρώματα @msg command `{0}` is not available right now: {1} η εντολή `{0}` δεν είναι διαθέσιμη αυτήν τη στιγμή: {1} @@ -5713,6 +5724,7 @@ variable-list-end {0}, {1} {0} και {1} @msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης @msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης @msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης +@msg a linked file's editing data can't be read to check it against the read roots τα δεδομένα επεξεργασίας ενός συνδεδεμένου αρχείου δεν μπορούν να διαβαστούν για έλεγχο με τις ρίζες ανάγνωσης @msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης @msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript @msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path} @@ -7785,6 +7797,7 @@ breakText Glyphs Γλύφοι @msg One path lies inside the other, so they have no common tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν κοινές εφαπτόμενες @msg The paths overlap, so they have no internal tangents Οι διαδρομές επικαλύπτονται, επομένως δεν έχουν εσωτερικές εφαπτόμενες @msg One path lies inside the other, so they have no internal tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν εσωτερικές εφαπτόμενες +@msg The point lies inside the path, so it has no tangents Το σημείο βρίσκεται μέσα στη διαδρομή, επομένως δεν έχει εφαπτόμενες # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Επέκταση παυλών σε διαδρομές @msg select paths with dashed strokes to expand επιλέξτε διαδρομές με διακεκομμένο περίγραμμα για επέκταση @@ -8292,4 +8305,9 @@ breakText Glyphs Γλύφοι @msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. @msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Pressure Sensitive Ευαίσθητα στην πίεση + Flex Ribbon Εύκαμπτη κορδέλα + Pulse Stroke Παλμική πινελιά + Round Flow Στρογγυλή ροή + Chisel Flow Λοξή ροή @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: χρησιμοποιήστε "{_1}" ή "{_2}" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5af6a75d82..d3ead234fd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -141,6 +141,7 @@ Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados Additional Plug-ins Folder Carpeta de plugins adicionales + Plug-in Instruction Budget Presupuesto de instrucciones de plugins Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos Incoming Entrante @@ -818,6 +819,7 @@ font-technology Variable Variables Delete Brush Eliminar pincel Delete Color Eliminar color Restore Generated Table Restaurar tabla generada + Unshift All Colors Deshacer cambio de todos los colores Delete Character Style Eliminar estilo de carácter Delete Empty Artboards Eliminar mesas de trabajo vacías Delete Freeform Point Eliminar punto libre @@ -3242,6 +3244,8 @@ digits Malayalam Malayálam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Cuánto debe acercarse en pantalla el puntero o un punto arrastrado a la ilustración para que las guías inteligentes se ajusten a ella; la distancia es la misma con cualquier zoom. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Ajusta el extremo de un segmento de línea, o un círculo dibujado desde su centro, para que toque una curva cercana. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Ajusta el extremo de un segmento de línea para que encuentre un segmento recto cercano en ángulo recto. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Muestra en el lienzo el número de cada sector en un recuadro en su esquina superior izquierda; si está desactivado, los contornos de los sectores siguen visibles. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. El color de los contornos de los sectores de usuario y de objeto y de los recuadros con su número; los sectores automáticos usan un tono más apagado de ese color. Reset all preferences to their defaults? ¿Restablecer todas las preferencias a sus valores predeterminados? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Los valores predeterminados se aplican al hacer clic en Aceptar en Preferencias. Cancelar ahí conserva sus preferencias actuales. Restore Recovered Documents Restaurar documentos recuperados @@ -3471,6 +3475,12 @@ digits Malayalam Malayálam Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos… No commands match Ningún comando coincide {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Sin elemento de menú + Toolbar Barra de herramientas + {toolbar}, in the {tool} group {toolbar}, en el grupo {tool} + In the menu bar: {path} En la barra de menús: {path} + In the {group} group: press and hold to open it En el grupo {group}: mantén pulsado para abrirlo + {home}, not shown now {home}, no se muestra ahora @plural {n} result|{n} results {n} resultado|{n} resultados @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos. Recent Commands Comandos recientes @@ -5087,6 +5097,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg choose a location for the package elige una ubicación para el paquete @msg clipboard is empty el portapapeles está vacío @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: al menos un color debe quedar en la tabla de colores +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` indica un color que también indica otra clave @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` no es un color como "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: como máximo {MAX_TABLE} colores @msg command `{0}` is not available right now: {1} el comando `{0}` no está disponible ahora: {1} @@ -5754,6 +5765,7 @@ variable-list-end {0}, {1} {0} y {1} @msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura @msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura @msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's editing data can't be read to check it against the read roots no se pueden leer los datos de edición de un archivo vinculado para comprobarlos con las carpetas raíz de lectura @msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path} @msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía @@ -7773,6 +7785,7 @@ breakText Glyphs Glifos @msg One path lies inside the other, so they have no common tangents Un trazado está dentro del otro, por lo que no tienen tangentes comunes @msg The paths overlap, so they have no internal tangents Los trazados se superponen, por lo que no tienen tangentes internas @msg One path lies inside the other, so they have no internal tangents Un trazado está dentro del otro, por lo que no tienen tangentes internas +@msg The point lies inside the path, so it has no tangents El punto está dentro del trazado, por lo que no tiene tangentes # 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 @@ -8279,4 +8292,9 @@ breakText Glyphs Glifos @msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. @msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Pressure Sensitive Sensible a la presión + Flex Ribbon Cinta flexible + Pulse Stroke Trazo pulsante + Round Flow Flujo redondo + Chisel Flow Flujo biselado @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: use "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1a3f52e96d..06a710fbca 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3530,6 +3530,7 @@ theme Appearance Ulkoasu Delete Brush Poista sivellin Delete Color Poista väri Restore Generated Table Palauta luotu taulukko + Unshift All Colors Peru kaikkien värien siirto Delete Symbol Poista symboli Delete the selected symbol? Poistetaanko valittu symboli? Delete the selected symbols? Poistetaanko valitut symbolit? @@ -3984,6 +3985,7 @@ theme Appearance Ulkoasu 90° & 45° Angles 90° ja 45° kulmat 90° Angles 90° kulmat Additional Plug-ins Folder Lisälaajennusten kansio + Plug-in Instruction Budget Laajennusten käskybudjetti Additional Fonts Folder Lisäfonttien kansio Alignment Guides Tasausapuviivat Anchor Points, Handle, and Bounding Box Display Ankkuripisteiden, kahvojen ja rajausruudun näyttö @@ -4502,6 +4504,12 @@ font-technology Variable Muuttuvat Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita… No commands match Mikään komento ei vastaa hakua {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Ei valikkokohdetta + Toolbar Työkalurivi + {toolbar}, in the {tool} group {toolbar}, ryhmässä {tool} + In the menu bar: {path} Valikkorivillä: {path} + In the {group} group: press and hold to open it Ryhmässä {group}: avaa painamalla pitkään + {home}, not shown now {home}, ei näkyvissä nyt @plural {n} result|{n} results {n} tulos|{n} tulosta @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia. Recent Commands Viimeisimmät komennot @@ -4619,6 +4627,8 @@ font-technology Variable Muuttuvat How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Kuinka lähelle grafiikkaa osoittimen tai vedettävän pisteen on tultava näytöllä, jotta älykkäät apuviivat kohdistavat siihen; etäisyys on sama kaikilla zoomauksilla. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Kohdistaa janan pään tai keskipisteestä piirretyn ympyrän niin, että se koskettaa lähellä olevaa käyrää. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Kohdistaa janan pään niin, että se kohtaa lähellä olevan suoran segmentin suorassa kulmassa. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Näyttää piirtopinnalla kunkin viipaleen numeron ruudussa sen vasemmassa yläkulmassa; kun asetus on pois päältä, viipaleiden ääriviivat näkyvät edelleen. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Käyttäjä- ja objektiviipaleiden ääriviivojen ja niiden numeroruutujen väri; automaattiset viipaleet käyttävät siitä himmeämpää sävyä. Reset all preferences to their defaults? Palautetaanko kaikki asetukset oletuksiin? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Oletukset otetaan käyttöön, kun valitset Asetuksissa OK. Peruuta siellä säilyttää nykyiset asetuksesi. Smaller ↔ Larger Pienempi ↔ Suurempi @@ -5303,6 +5313,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg choose a location for the package valitse paketin sijainti @msg clipboard is empty leikepöytä on tyhjä @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: väritaulukkoon on jäätävä vähintään yksi väri +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` nimeää värin, jonka myös toinen avain nimeää @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ei ole väri, kuten "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: enintään {MAX_TABLE} väriä @msg command `{0}` is not available right now: {1} komento `{0}` ei ole nyt käytettävissä: {1} @@ -5936,6 +5947,7 @@ variable-list-end {0}, {1} {0} ja {1} @msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella @msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella @msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella +@msg a linked file's editing data can't be read to check it against the read roots linkitetyn tiedoston muokkaustietoja ei voi lukea niiden tarkistamiseksi lukujuuria vasten @msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella @msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa @msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path} @@ -7861,6 +7873,7 @@ breakText Glyphs Merkit @msg One path lies inside the other, so they have no common tangents Toinen polku on toisen sisällä, joten niillä ei ole yhteisiä tangentteja @msg The paths overlap, so they have no internal tangents Polut ovat päällekkäin, joten niillä ei ole sisäisiä tangentteja @msg One path lies inside the other, so they have no internal tangents Toinen polku on toisen sisällä, joten niillä ei ole sisäisiä tangentteja +@msg The point lies inside the path, so it has no tangents Piste on polun sisällä, joten sillä ei ole tangentteja # 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 @@ -8375,4 +8388,9 @@ breakText Glyphs Merkit @msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. @msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Pressure Sensitive Paineherkkä + Flex Ribbon Joustava nauha + Pulse Stroke Sykkivä veto + Round Flow Pyöreä veto + Chisel Flow Viisto veto @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: käytä arvoa "{_1}" tai "{_2}" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e2adbffc29..60bc389a9a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -142,6 +142,7 @@ Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées Additional Plug-ins Folder Dossier de modules externes supplémentaires + Plug-in Instruction Budget Budget d’instructions des modules externes Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents Incoming Entrant @@ -820,6 +821,7 @@ font-technology Variable Variables Delete Brush Supprimer la forme Delete Color Supprimer la couleur Restore Generated Table Restaurer la table générée + Unshift All Colors Annuler le décalage de toutes les couleurs Delete Character Style Supprimer le style de caractère Delete Empty Artboards Supprimer les plans de travail vides Delete Freeform Point Supprimer le point libre @@ -3230,6 +3232,8 @@ digits Malayalam Malayalam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. La distance à l’écran à laquelle le pointeur ou un point déplacé doit approcher une illustration pour que les repères commentés s’y aimantent. Elle est la même à tous les zooms. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Aimante l’extrémité d’un segment de droite, ou un cercle tracé depuis son centre, pour qu’il touche une courbe proche. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Aimante l’extrémité d’un segment de droite pour qu’il rencontre un segment droit proche à angle droit. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Affiche sur la zone de travail le numéro de chaque tranche dans un cadre en haut à gauche de la tranche. Désactivée, les contours des tranches restent affichés. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. La couleur des contours des tranches utilisateur et objet et de leurs cadres de numéro. Les tranches automatiques utilisent une nuance plus terne de cette couleur. Reset all preferences to their defaults? Rétablir toutes les préférences à leur valeur par défaut ? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Les valeurs par défaut sont appliquées lorsque vous cliquez sur OK dans Préférences. Annuler y conserve vos préférences actuelles. Restore Recovered Documents Restaurer les documents récupérés @@ -3459,6 +3463,12 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets… No commands match Aucune commande ne correspond {pos} of {total}: {name} {pos} sur {total} : {name} + No menu item Aucun élément de menu + Toolbar Barre d’outils + {toolbar}, in the {tool} group {toolbar}, dans le groupe {tool} + In the menu bar: {path} Dans la barre des menus, sous {path} + In the {group} group: press and hold to open it Dans le groupe {group}, maintenez enfoncé pour l’ouvrir + {home}, not shown now {home}, non affiché pour l’instant @plural {n} result|{n} results {n} résultat|{n} résultats @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner. Recent Commands Commandes récentes @@ -5046,6 +5056,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg choose a location for the package choisissez un emplacement pour l’assemblage @msg clipboard is empty le presse-papiers est vide @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: au moins une couleur doit rester dans la table des couleurs +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` désigne une couleur qu’une autre clé désigne aussi @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what} : `{h}` n’est pas une couleur comme "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what} : {MAX_TABLE} couleurs au maximum @msg command `{0}` is not available right now: {1} la commande `{0}` n’est pas disponible pour le moment : {1} @@ -5731,6 +5742,7 @@ variable-list-end {0}, {1} {0} et {1} @msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture @msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture @msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture +@msg a linked file's editing data can't be read to check it against the read roots impossible de lire les données d’édition d’un fichier lié pour les vérifier par rapport aux dossiers racines de lecture @msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path} @msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path} @msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide @@ -7793,6 +7805,7 @@ breakText Glyphs Glyphes @msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune @msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne @msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne +@msg The point lies inside the path, so it has no tangents Le point se trouve à l’intérieur du tracé et n’a donc aucune tangente # 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 @@ -10099,3 +10112,8 @@ breakText Glyphs Glyphes @msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. @msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Pressure Sensitive Sensible à la pression + Flex Ribbon Ruban souple + Pulse Stroke Trait pulsé + Round Flow Flux rond + Chisel Flow Flux biseauté diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index bc7293c18d..139a5b2db9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -164,6 +164,7 @@ Add to the Current Shortcuts વર્તમાન શૉર્ટકટમાં ઉમેરો Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર + Plug-in Instruction Budget પ્લગ-ઇન સૂચના બજેટ Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો Incoming આવતી બાજુ Outgoing જતી બાજુ @@ -923,6 +924,7 @@ Delete Brush બ્રશ કાઢી નાખો Delete Color રંગ કાઢી નાખો Restore Generated Table જનરેટ થયેલું ટેબલ પુનઃસ્થાપિત કરો + Unshift All Colors બધા રંગોનું શિફ્ટ રદ કરો Delete Character Style અક્ષર સ્ટાઇલ કાઢી નાખો Delete Data Set ડેટા સેટ કાઢી નાખો Delete Data Sets ડેટા સેટ્સ કાઢી નાખો @@ -3084,6 +3086,7 @@ @msg One path lies inside the other, so they have no common tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ સામાન્ય સ્પર્શરેખા નથી @msg The paths overlap, so they have no internal tangents પાથ એકબીજા પર ચઢેલા છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી @msg One path lies inside the other, so they have no internal tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી +@msg The point lies inside the path, so it has no tangents બિંદુ પાથની અંદર છે, તેથી તેની કોઈ સ્પર્શરેખા નથી Remove Guide ગાઇડ દૂર કરો Remove Item આઇટમ દૂર કરો Remove JavaScript File JavaScript ફાઇલ દૂર કરો @@ -3301,6 +3304,8 @@ How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. સ્માર્ટ ગાઇડ સ્નેપ કરે તે માટે પોઇન્ટર અથવા ખેંચેલું બિંદુ સ્ક્રીન પર આર્ટની કેટલું નજીક આવવું જોઈએ; આ અંતર દરેક ઝૂમ પર સમાન રહે છે. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. લાઇન સેગમેન્ટના છેડાને, અથવા કેન્દ્રથી દોરેલા વર્તુળને, એ રીતે સ્નેપ કરે છે કે તે નજીકના વળાંકને સ્પર્શે. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. લાઇન સેગમેન્ટના છેડાને એ રીતે સ્નેપ કરે છે કે તે નજીકના સીધા સેગમેન્ટને કાટખૂણે મળે. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. કેનવાસ પર દરેક સ્લાઇસનો નંબર તેના ઉપરના ડાબા ખૂણે એક બૉક્સમાં બતાવે છે; બંધ હોય ત્યારે પણ સ્લાઇસની રૂપરેખાઓ દેખાય છે. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. યુઝર અને ઑબ્જેક્ટ સ્લાઇસની રૂપરેખાઓ અને તેમના નંબર બૉક્સનો રંગ; ઑટો સ્લાઇસ તેની ઝાંખી છાયા વાપરે છે. Restored documents open unsaved: save them to keep them. પુનઃસ્થાપિત દસ્તાવેજો અસાચવેલા ખુલશે: તેમને રાખવા માટે સાચવો. Restrict printing, editing and other tasks છાપકામ, સંપાદન અને અન્ય કાર્યો પર પ્રતિબંધ મૂકો Reticulation… રેટિક્યુલેશન… @@ -3568,6 +3573,15 @@ Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો… No commands match કોઈ આદેશ મેળ ખાતો નથી {pos} of {total}: {name} {total} માંથી {pos}: {name} + No menu item કોઈ મેનૂ આઇટમ નથી + Toolbar ટૂલબાર + {toolbar}, in the {tool} group {toolbar}, {tool} જૂથમાં + In the menu bar: {path} મેનૂ બારમાં: {path} + In the {group} group: press and hold to open it {group} જૂથમાં: ખોલવા માટે દબાવીને પકડી રાખો + {home}, not shown now {home}, હમણાં બતાવેલ નથી + Tool ટૂલ + Command કમાન્ડ + Panel પેનલ @plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો. Recent Commands તાજેતરના આદેશો @@ -5099,3 +5113,8 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Pressure Sensitive દબાણ સંવેદનશીલ + Flex Ribbon લવચીક પટ્ટી + Pulse Stroke ધબકતો ઘસારો + Round Flow ગોળ પ્રવાહ + Chisel Flow ત્રાંસો પ્રવાહ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e63af675f2..0ca6ee299a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -257,6 +257,7 @@ Add Used Colors उपयोग किए रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर + Plug-in Instruction Budget प्लग-इन निर्देश बजट Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें Incoming आने वाली ओर Outgoing जाने वाली ओर @@ -1318,6 +1319,7 @@ antiAlias Sharp शार्प Delete Brush ब्रश हटाएँ Delete Color रंग हटाएँ Restore Generated Table जनरेट की गई तालिका पुनर्स्थापित करें + Unshift All Colors सभी रंग अनशिफ़्ट करें Delete Character Style कैरेक्टर स्टाइल हटाएँ Delete Data Set डेटा सेट हटाएँ Delete Data Sets डेटा सेट्स हटाएँ @@ -4355,6 +4357,8 @@ antiAlias Sharp शार्प How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. स्मार्ट गाइड्स के स्नैप करने के लिए पॉइंटर या ड्रैग किया गया पॉइंट स्क्रीन पर आर्ट के कितने पास आना चाहिए; यह दूरी हर ज़ूम पर समान रहती है। Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. लाइन सेगमेंट के सिरे को, या केंद्र से ड्रॉ किए गए वृत्त को, इस तरह स्नैप करता है कि वह पास के वक्र को छुए। Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. लाइन सेगमेंट के सिरे को इस तरह स्नैप करता है कि वह पास के सीधे सेगमेंट से समकोण पर मिले। + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. कैनवास पर हर स्लाइस का नंबर उसके ऊपरी बाएँ कोने में एक बॉक्स में दिखाता है; बंद होने पर भी स्लाइस की आउटलाइन दिखती रहती हैं। + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. यूज़र और ऑब्जेक्ट स्लाइस की आउटलाइन और उनके नंबर बॉक्स का रंग; ऑटो स्लाइस इसकी हल्की छाया इस्तेमाल करते हैं। Reset all preferences to their defaults? सभी प्रेफ़रेंसेज़ को उनके डिफ़ॉल्ट पर रीसेट करें? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. डिफ़ॉल्ट तब लागू होते हैं जब आप प्रेफ़रेंसेज़ में ठीक है पर क्लिक करते हैं। वहाँ रद्द करें आपकी मौजूदा प्रेफ़रेंसेज़ बनाए रखता है। Restore Recovered Documents पुनर्स्थापना डॉक्यूमेंट @@ -4653,6 +4657,12 @@ antiAlias Sharp शार्प Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें… No commands match कोई आदेश मेल नहीं खाता {pos} of {total}: {name} {total} में से {pos}: {name} + No menu item कोई मेनू आइटम नहीं + Toolbar टूलबार + {toolbar}, in the {tool} group {toolbar}, {tool} समूह में + In the menu bar: {path} मेनू बार में: {path} + In the {group} group: press and hold to open it {group} समूह में: खोलने के लिए दबाकर रखें + {home}, not shown now {home}, अभी नहीं दिखाया गया @plural {n} result|{n} results {n} परिणाम|{n} परिणाम @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें। Recent Commands हाल के आदेश @@ -6852,6 +6862,7 @@ antiAlias Sharp शार्प @msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है @msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है @msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है +@msg a linked file's editing data can't be read to check it against the read roots एक लिंक की गई फ़ाइल का संपादन डेटा पढ़ने की जड़ों से जाँचने के लिए पढ़ा नहीं जा सकता @msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है @msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है @msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} @@ -6975,6 +6986,7 @@ antiAlias Sharp शार्प @msg colorMode must be rgb or cmyk, not `{m}` colorMode को rgb या cmyk होना चाहिए, `{m}` नहीं @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel को {own} (डॉक्यूमेंट का मोड), grayscale या bitmap होना चाहिए @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: रंग तालिका में कम से कम एक रंग रहना चाहिए +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` वही रंग बताता है जो कोई दूसरी कुंजी भी बताती है @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" जैसा रंग नहीं है @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: अधिकतम {MAX_TABLE} रंग @msg colour groups can't go into colour groups रंग समूह रंग समूहों में नहीं जा सकते हैं @@ -8452,6 +8464,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg One path lies inside the other, so they have no common tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई उभयनिष्ठ स्पर्शरेखा नहीं है @msg The paths overlap, so they have no internal tangents पाथ एक-दूसरे पर चढ़े हुए हैं, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है @msg One path lies inside the other, so they have no internal tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है +@msg The point lies inside the path, so it has no tangents बिंदु पाथ के अंदर है, इसलिए उसकी कोई स्पर्शरेखा नहीं है @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select two or three paths or compound paths दो या तीन पाथ या यौगिक पाथ सिलेक्ट करें @@ -9709,6 +9722,11 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Pressure Sensitive दबाव संवेदनशील + Flex Ribbon लचीला फीता + Pulse Stroke स्पंदित रेखा + Round Flow गोल प्रवाह + Chisel Flow तिरछा प्रवाह Fold Preview फ़ोल्ड प्रीव्यू Fold फ़ोल्ड Show Fold Lines फ़ोल्ड लाइनें दिखाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 68a8c82cf2..79d6bcb16d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -211,6 +211,7 @@ Add Used Colors Használt színek hozzáadása Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája + Plug-in Instruction Budget Bővítmények utasításkerete Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása Incoming Bejövő Outgoing Kimenő @@ -1047,6 +1048,7 @@ font-technology Variable Változó Delete Brush Ecset törlése Delete Color Szín törlése Restore Generated Table Előállított tábla visszaállítása + Unshift All Colors Az összes szín eltolásának visszavonása Delete Character Style Karakterstílus törlése Delete Data Set Adatkészlet törlése Delete Empty Artboards Üres rajztáblák törlése @@ -3823,6 +3825,8 @@ mark-style Japanese Japán How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Milyen közel kell a mutatónak vagy egy húzott pontnak a képernyőn a grafikához érnie, hogy az intelligens segédvonalak illesszenek; a távolság minden nagyításnál azonos. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Egy szakasz végét vagy a középpontjából rajzolt kört úgy illeszti, hogy érintse a közeli görbét. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Egy szakasz végét úgy illeszti, hogy derékszögben találkozzon egy közeli egyenes szakasszal. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. A vásznon minden szelet számát egy keretben mutatja a szelet bal felső sarkában; kikapcsolva a szeletek körvonalai továbbra is látszanak. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. A felhasználói és objektumszeletek körvonalainak és számkereteinek színe; az automatikus szeletek ennek egy halványabb árnyalatát használják. Reset all preferences to their defaults? Visszaállítja az összes beállítást az alapértékre? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Az alapértékek akkor lépnek életbe, amikor a Beállításokban az OK gombra kattint. Az ottani Mégse megtartja a jelenlegi beállításokat. Restore Recovered Documents Helyreállított dokumentumok visszaállítása @@ -4094,6 +4098,12 @@ mark-style Japanese Japán Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése… No commands match Nincs egyező parancs {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Nincs menüpont + Toolbar Eszköztár + {toolbar}, in the {tool} group {toolbar}, a(z) {tool} csoportjában + In the menu bar: {path} A menüsorban: {path} + In the {group} group: press and hold to open it A(z) {group} csoportban: a megnyitáshoz nyomja le és tartsa lenyomva + {home}, not shown now {home}, most nem látható @plural {n} result|{n} results {n} találat @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez. Recent Commands Legutóbbi parancsok @@ -5399,6 +5409,7 @@ imageTrace Outline Körvonal @msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken @msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken @msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken +@msg a linked file's editing data can't be read to check it against the read roots egy csatolt fájl szerkesztési adatai nem olvashatók be az olvasási gyökerekkel való ellenőrzéshez @msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path} @msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path} @@ -5449,6 +5460,7 @@ imageTrace Outline Körvonal @msg clipboard is empty a vágólap üres @msg closing needs three anchors a lezáráshoz három horgonypont kell @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: legalább egy színnek a színtáblában kell maradnia +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: a(z) `{k}` olyan színt nevez meg, amelyet egy másik kulcs is megnevez @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nem szín (például "#ff8800") @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: legfeljebb {MAX_TABLE} szín @msg column must be true or a number from 1 a column értéke true vagy 1-től kezdődő szám lehet @@ -7782,6 +7794,7 @@ breakText Glyphs Glifák @msg One path lies inside the other, so they have no common tangents Az egyik útvonal a másikon belül van, így nincsenek közös érintőik @msg The paths overlap, so they have no internal tangents Az útvonalak átfedik egymást, így nincsenek belső érintőik @msg One path lies inside the other, so they have no internal tangents Az egyik útvonal a másikon belül van, így nincsenek belső érintőik +@msg The point lies inside the path, so it has no tangents A pont az útvonalon belül van, így nincsenek érintői # 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 @@ -10091,6 +10104,11 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Pressure Sensitive Nyomásérzékeny + Flex Ribbon Rugalmas szalag + Pulse Stroke Lüktető vonás + Round Flow Kerek vonás + Chisel Flow Ferde vonás Fold Preview Hajtás előnézete Fold Hajtás Show Fold Lines Hajtásvonalak megjelenítése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b5ca49a56b..63d3c06972 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3262,6 +3262,7 @@ theme Appearance Tampilan Delete Brush Hapus kuas Delete Color Hapus warna Restore Generated Table Pulihkan tabel yang dibuat + Unshift All Colors Batalkan pergeseran semua warna Delete Symbol Hapus simbol Delete the selected symbol? Hapus simbol yang dipilih? Delete the selected symbols? Hapus simbol yang dipilih? @@ -3715,6 +3716,7 @@ theme Appearance Tampilan 90° & 45° Angles Sudut 90° & 45° 90° Angles Sudut 90° Additional Plug-ins Folder Folder plug-in tambahan + Plug-in Instruction Budget Anggaran instruksi plug-in Additional Fonts Folder Folder font tambahan Alignment Guides Panduan perataan Anchor Points, Handle, and Bounding Box Display Tampilan titik jangkar, pegangan, dan kotak pembatas @@ -4227,6 +4229,12 @@ font-technology Variable Variabel Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek… No commands match Tidak ada perintah yang cocok {pos} of {total}: {name} {pos} dari {total}: {name} + No menu item Tidak ada item menu + Toolbar Bilah alat + {toolbar}, in the {tool} group {toolbar}, dalam grup {tool} + In the menu bar: {path} Di bilah menu: {path} + In the {group} group: press and hold to open it Di grup {group}: tekan dan tahan untuk membukanya + {home}, not shown now {home}, tidak ditampilkan sekarang @plural {n} result|{n} results {n} hasil @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya. Recent Commands Perintah terbaru @@ -4344,6 +4352,8 @@ font-technology Variable Variabel How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Seberapa dekat penunjuk atau titik yang diseret harus mendekati karya di layar agar panduan cerdas menjepret; jaraknya sama pada setiap zoom. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Menjepretkan ujung segmen garis, atau lingkaran yang digambar dari pusatnya, agar menyentuh kurva di dekatnya. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Menjepretkan ujung segmen garis agar bertemu segmen lurus di dekatnya pada sudut siku-siku. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Menampilkan nomor setiap irisan dalam kotak di sudut kiri atasnya di kanvas; saat nonaktif, garis tepi irisan tetap ditampilkan. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Warna garis tepi irisan pengguna dan objek serta kotak nomornya; irisan otomatis memakai nuansa yang lebih redup dari warna ini. Reset all preferences to their defaults? Atur ulang semua preferensi ke defaultnya? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Nilai default diterapkan saat Anda mengklik OK di Preferensi. Batal di sana mempertahankan preferensi Anda saat ini. Smaller ↔ Larger Lebih kecil ↔ Lebih besar @@ -4787,6 +4797,7 @@ imageTrace Outline Kontur @msg choose a location for the package pilih lokasi untuk paket @msg clipboard is empty papan klip kosong @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: setidaknya satu warna harus tetap ada di tabel warna +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` menyebut warna yang juga disebut kunci lain @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` bukan warna seperti "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maksimal {MAX_TABLE} warna @msg command `{0}` is not available right now: {1} perintah `{0}` tidak tersedia saat ini: {1} @@ -7041,6 +7052,7 @@ breakText Glyphs Glif @msg One path lies inside the other, so they have no common tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung persekutuan @msg The paths overlap, so they have no internal tangents Jalur-jalur saling tumpang tindih, sehingga tidak ada garis singgung dalam @msg One path lies inside the other, so they have no internal tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung dalam +@msg The point lies inside the path, so it has no tangents Titik berada di dalam jalur, sehingga tidak ada garis singgung # 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 @@ -7383,3 +7395,8 @@ breakText Glyphs Glif @msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. @msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Pressure Sensitive Peka Tekanan + Flex Ribbon Pita Lentur + Pulse Stroke Goresan Berdenyut + Round Flow Aliran Bulat + Chisel Flow Aliran Serong diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c09271ca2b..e4ca09e0ea 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -141,6 +141,7 @@ Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati Additional Plug-ins Folder Cartella plug-in aggiuntivi + Plug-in Instruction Budget Budget di istruzioni dei plug-in Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti Incoming In entrata @@ -820,6 +821,7 @@ font-technology Variable Variabili Delete Brush Elimina pennello Delete Color Elimina colore Restore Generated Table Ripristina tabella generata + Unshift All Colors Annulla spostamento di tutti i colori Delete Character Style Elimina stile carattere Delete Empty Artboards Elimina tavole da disegno vuote Delete Freeform Point Elimina punto libero @@ -3290,6 +3292,8 @@ digits Malayalam Malayalam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Quanto vicino sullo schermo il puntatore o un punto trascinato deve arrivare alla grafica perché le guide sensibili vi si aggancino; la distanza è la stessa a ogni zoom. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Aggancia l’estremità di un segmento di linea, o un cerchio disegnato dal centro, in modo che tocchi una curva vicina. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Aggancia l’estremità di un segmento di linea in modo che incontri un segmento rettilineo vicino ad angolo retto. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra sull’area di lavoro il numero di ogni sezione in un riquadro nel suo angolo in alto a sinistra; se è disattivata, i contorni delle sezioni restano visibili. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Il colore dei contorni delle sezioni utente e oggetto e dei riquadri con il loro numero; le sezioni automatiche usano una tonalità più tenue di questo colore. Reset all preferences to their defaults? Ripristinare tutte le preferenze ai valori predefiniti? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. I valori predefiniti vengono applicati quando fai clic su OK in Preferenze. Annulla lì mantiene le preferenze attuali. Restore Recovered Documents Ripristina documenti recuperati @@ -3521,6 +3525,14 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti… No commands match Nessun comando corrisponde {pos} of {total}: {name} {pos} di {total}: {name} + No menu item Nessuna voce di menu + Toolbar Barra degli strumenti + {toolbar}, in the {tool} group {toolbar}, nel gruppo {tool} + In the menu bar: {path} Nella barra dei menu: {path} + In the {group} group: press and hold to open it Nel gruppo {group}: tieni premuto per aprirlo + {home}, not shown now {home}, ora non visibile + Tool Strumento + Command Comando @plural {n} result|{n} results {n} risultato|{n} risultati @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli. Recent Commands Comandi recenti @@ -5111,6 +5123,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg choose a location for the package scegli una posizione per il pacchetto @msg clipboard is empty gli appunti sono vuoti @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: almeno un colore deve restare nella tabella colori +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` indica un colore indicato anche da un’altra chiave @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` non è un colore come "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: al massimo {MAX_TABLE} colori @msg command `{0}` is not available right now: {1} il comando `{0}` non è disponibile in questo momento: {1} @@ -5774,6 +5787,7 @@ variable-list-end {0}, {1} {0} e {1} @msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura @msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura @msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura +@msg a linked file's editing data can't be read to check it against the read roots impossibile leggere i dati di modifica di un file collegato per verificarli rispetto alle cartelle radice di lettura @msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path} @msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto @@ -7422,6 +7436,7 @@ breakText Glyphs Glifi @msg One path lies inside the other, so they have no common tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti comuni @msg The paths overlap, so they have no internal tangents I tracciati si sovrappongono, quindi non hanno tangenti interne @msg One path lies inside the other, so they have no internal tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti interne +@msg The point lies inside the path, so it has no tangents Il punto si trova dentro il tracciato, quindi non ha tangenti # 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 @@ -9740,6 +9755,11 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Pressure Sensitive Sensibile alla pressione + Flex Ribbon Nastro flessibile + Pulse Stroke Tratto pulsante + Round Flow Flusso tondo + Chisel Flow Flusso obliquo Fold Preview Anteprima piegatura Fold Piegatura Show Fold Lines Mostra linee di piega diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d3b9bef584..4caa8ba8db 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1093,6 +1093,7 @@ digits Malayalam マラヤーラム数字 Add to Selection 選択範囲に追加 Add to Swatches スウォッチに追加 Additional Plug-ins Folder 追加プラグインフォルダー + Plug-in Instruction Budget プラグインの命令予算 Additional Fonts Folder 追加フォントフォルダー Adjust Adjoining Width Points 隣接する幅ポイントを調整 Incoming 入り側 @@ -1521,6 +1522,7 @@ antiAlias Sharp シャープ Delete Brush ブラシを削除 Delete Color カラーを削除 Restore Generated Table 生成されたテーブルを復元 + Unshift All Colors すべてのカラーのシフトを戻す Delete Character Style 文字スタイルを削除 Delete Empty Artboards 空のアートボードを削除 Delete Freeform Point フリーフォームポイントを削除 @@ -3274,6 +3276,8 @@ mark-style Japanese 日本式 How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. スマートガイドがスナップするために、ポインターやドラッグしたポイントが画面上でアートにどこまで近づく必要があるかです。この距離はどのズームでも同じです。 Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 直線セグメントの端、または中心から描いた円を、近くの曲線に接するようにスナップします。 Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 直線セグメントの端を、近くの直線セグメントと直角に交わるようにスナップします。 + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. カンバス上で、各スライスの番号をスライスの左上のボックスに表示します。オフでもスライスの輪郭は表示されます。 + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. ユーザースライスとオブジェクトスライスの輪郭、およびその番号のボックスの色です。自動スライスにはこの色の淡い色合いが使われます。 Reset all preferences to their defaults? すべての環境設定を初期値に戻しますか? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 初期値は環境設定で OK をクリックすると適用されます。そこでキャンセルすると現在の環境設定が保たれます。 Restored documents open unsaved: save them to keep them. 復元したドキュメントは未保存の状態で開きます。保存して残してください。 @@ -3406,6 +3410,12 @@ mark-style Japanese 日本式 Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索… No commands match 一致するコマンドはありません {pos} of {total}: {name} {total} 件中 {pos} 件目: {name} + No menu item メニュー項目なし + Toolbar ツールバー + {toolbar}, in the {tool} group {toolbar}、{tool} のグループ内 + In the menu bar: {path} メニューバー: {path} + In the {group} group: press and hold to open it {group} のグループ内: 長押しで開きます + {home}, not shown now {home}、現在は表示されていません @plural {n} result|{n} results {n} 件 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} 件中 {shown} 件。続けて入力すると絞り込めます。 Recent Commands 最近使ったコマンド @@ -5076,6 +5086,7 @@ variable-list-end {0}, {1} {0}、{1} @msg paste unavailable 貼り付けを使用できません @msg Save for Web: the image is empty Web 用に保存: 画像が空です @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: カラーテーブルには少なくとも 1 つのカラーを残す必要があります +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` は別のキーと同じカラーを指しています @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` は「#ff8800」のような形式のカラーではありません @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 指定できるカラーは {MAX_TABLE} 色までです @msg no artboard {i} (0-based; the document has {_1}) アートボード {i} はありません (番号は 0 始まり、このドキュメントには {_1} 個あります) @@ -5824,6 +5835,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります @msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります @msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります +@msg a linked file's editing data can't be read to check it against the read roots リンクされたファイルの編集データを読み込めないため、読み込みルートと照合できません @msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path} @msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path} @msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です @@ -9314,6 +9326,7 @@ breakText Glyphs 字形 @msg One path lies inside the other, so they have no common tangents 一方のパスがもう一方の内側にあるため、共通接線はありません @msg The paths overlap, so they have no internal tangents パスが重なっているため、内側の接線はありません @msg One path lies inside the other, so they have no internal tangents 一方のパスがもう一方の内側にあるため、内側の接線はありません +@msg The point lies inside the path, so it has no tangents 点がパスの内側にあるため、接線はありません # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 破線をパスに拡張 @msg select paths with dashed strokes to expand 拡張する破線のパスを選択してください @@ -9807,6 +9820,11 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Pressure Sensitive 筆圧対応 + Flex Ribbon しなやかなリボン + Pulse Stroke 脈打つ線 + Round Flow 丸筆の流れ + Chisel Flow 平筆の流れ Fold Preview 折りプレビュー Fold 折り Show Fold Lines 折り線を表示 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cc03030df2..0158c52367 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2066,6 +2066,7 @@ @msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} @msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა @msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's editing data can't be read to check it against the read roots დაკავშირებული ფაილის რედაქტირების მონაცემების წაკითხვა ვერ ხერხდება წაკითხვის ძირეულ საქაღალდეებთან შესამოწმებლად Neon & Glow ნეონი და ნათება Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან @msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] @@ -5355,6 +5356,7 @@ theme Appearance იერსახე Delete Brush ფუნჯის წაშლა Delete Color ფერის წაშლა Restore Generated Table გენერირებული ცხრილის აღდგენა + Unshift All Colors ყველა ფერის წანაცვლების მოხსნა Delete Symbol სიმბოლოს წაშლა Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? Delete the selected symbols? წაიშალოს მონიშნული სიმბოლოები? @@ -5809,6 +5811,7 @@ theme Appearance იერსახე 90° & 45° Angles 90° და 45° კუთხეები 90° Angles 90° კუთხეები Additional Plug-ins Folder დამატებითი პლაგინები + Plug-in Instruction Budget პლაგინების ინსტრუქციების ბიუჯეტი Additional Fonts Folder შრიფტების დამატებითი საქაღალდე Alignment Guides გასწორების დამხმარე ხაზები Anchor Points, Handle, and Bounding Box Display საყრდენი წერტილების, სახელურებისა და შემომსაზღვრელი ჩარჩოს ჩვენება @@ -6297,6 +6300,12 @@ font-technology Variable ცვლადი Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება… No commands match შესაბამისი ბრძანება არ არის {pos} of {total}: {name} {pos} / {total}: {name} + No menu item მენიუს ელემენტი არ არის + Toolbar ხელსაწყოთა ზოლი + {toolbar}, in the {tool} group {toolbar}, ჯგუფში {tool} + In the menu bar: {path} მენიუს ზოლში: {path} + In the {group} group: press and hold to open it ჯგუფში {group}: გასახსნელად დააჭირეთ და გეჭიროთ + {home}, not shown now {home}, ახლა არ ჩანს @plural {n} result|{n} results {n} შედეგი @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} შედეგიდან {shown}. გააგრძელეთ აკრეფა მათ შესამცირებლად. Recent Commands ბოლოდროინდელი ბრძანებები @@ -6415,6 +6424,8 @@ font-technology Variable ცვლადი How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. რამდენად ახლოს უნდა მივიდეს ეკრანზე მაჩვენებელი ან გადათრეული წერტილი გრაფიკასთან, რომ ჭკვიანმა დამხმარე ხაზებმა მიაბან; მანძილი ყველა მასშტაბზე ერთნაირია. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. ხაზის სეგმენტის ბოლოს, ან ცენტრიდან დახატულ წრეწირს, ისე აბამს, რომ ახლომდებარე მრუდს შეეხოს. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. ხაზის სეგმენტის ბოლოს ისე აბამს, რომ ახლომდებარე სწორ სეგმენტს მართი კუთხით შეხვდეს. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. ტილოზე თითოეული ნაჭრის ნომერს აჩვენებს ჩარჩოში მის ზედა მარცხენა კუთხეში; გამორთულისას ნაჭრების კონტურები კვლავ ჩანს. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. მომხმარებლისა და ობიექტის ნაჭრების კონტურებისა და მათი ნომრების ჩარჩოების ფერი; ავტომატური ნაჭრები ამ ფერის უფრო მკრთალ ელფერს იყენებს. Reset all preferences to their defaults? დავაბრუნოთ ყველა პარამეტრი ნაგულისხმევ მნიშვნელობებზე? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. ნაგულისხმევი მნიშვნელობები გამოიყენება, როცა პარამეტრებში OK-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. Smaller ↔ Larger უფრო პატარა ↔ უფრო დიდი @@ -6853,6 +6864,7 @@ font-technology Variable ცვლადი @msg choose a location for the package აირჩიეთ შეფუთვის მდებარეობა @msg clipboard is empty გაცვლის ბუფერი ცარიელია @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: ფერების ცხრილში ერთი ფერი მაინც უნდა დარჩეს +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` ასახელებს ფერს, რომელსაც სხვა გასაღებიც ასახელებს @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ფერი არ არის, მაგალითად "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: არაუმეტეს {MAX_TABLE} ფერი @msg command `{0}` is not available right now: {1} ბრძანება `{0}` ახლა ხელმისაწვდომი არ არის: {1} @@ -9995,6 +10007,7 @@ breakText Glyphs გლიფები @msg One path lies inside the other, so they have no common tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ საერთო მხებები არ აქვთ @msg The paths overlap, so they have no internal tangents ტრაექტორიები ერთმანეთს ფარავს, ამიტომ მათ შიდა მხებები არ აქვთ @msg One path lies inside the other, so they have no internal tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ შიდა მხებები არ აქვთ +@msg The point lies inside the path, so it has no tangents წერტილი ტრაექტორიის შიგნითაა, ამიტომ მას მხებები არ აქვს # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths ტირეების ტრაექტორიებად გაშლა @msg select paths with dashed strokes to expand აირჩიეთ გასაშლელი ტირეებიანი ხაზის კონტურები @@ -10456,3 +10469,8 @@ font-script Japanese იაპონური @msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. @msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Pressure Sensitive წნევაზე მგრძნობიარე + Flex Ribbon მოქნილი ლენტი + Pulse Stroke პულსირებადი მონასმი + Round Flow მრგვალი ნაკადი + Chisel Flow დახრილი ნაკადი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4fa5ba90d8..a877bb5299 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1083,6 +1083,7 @@ digits Malayalam 말라얄람어 Add to Selection 선택 영역에 추가 Add to Swatches 견본에 추가 Additional Plug-ins Folder 추가 플러그인 폴더 + Plug-in Instruction Budget 플러그인 명령어 예산 Additional Fonts Folder 추가 글꼴 폴더 Adjust Adjoining Width Points 인접한 너비 점 조정 Incoming 들어오는 쪽 @@ -1511,6 +1512,7 @@ antiAlias Sharp 날카롭게 Delete Brush 브러시 삭제 Delete Color 색상 삭제 Restore Generated Table 생성된 표 복원 + Unshift All Colors 모든 색상 이동 취소 Delete Character Style 문자 스타일 삭제 Delete Empty Artboards 빈 아트보드 삭제 Delete Freeform Point 자유 형태 포인트 삭제 @@ -3263,6 +3265,8 @@ mark-style Japanese 일본식 How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. 스마트 안내선이 스냅하려면 포인터나 드래그한 점이 화면에서 아트에 얼마나 가까이 와야 하는지입니다. 이 거리는 모든 확대/축소에서 같습니다. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 선 세그먼트의 끝이나 중심에서 그린 원을 가까운 곡선에 닿도록 스냅합니다. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 선 세그먼트의 끝을 가까운 직선 세그먼트와 직각으로 만나도록 스냅합니다. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 캔버스에서 각 슬라이스의 번호를 왼쪽 위의 상자에 표시합니다. 끄더라도 슬라이스 윤곽선은 계속 표시됩니다. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 사용자 슬라이스와 개체 슬라이스의 윤곽선 및 번호 상자의 색상입니다. 자동 슬라이스에는 이 색상의 더 흐린 색조가 사용됩니다. Reset all preferences to their defaults? 모든 환경 설정을 기본값으로 재설정하시겠습니까? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 기본값은 환경 설정에서 확인을 클릭하면 적용됩니다. 그곳에서 취소를 누르면 현재 환경 설정이 유지됩니다. Restored documents open unsaved: save them to keep them. 복원된 문서는 저장되지 않은 상태로 열립니다. 보존하려면 저장하세요. @@ -3395,6 +3399,14 @@ mark-style Japanese 일본식 Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색… No commands match 일치하는 명령이 없습니다 {pos} of {total}: {name} {total}개 중 {pos}번째: {name} + No menu item 메뉴 항목 없음 + Toolbar 도구 모음 + {toolbar}, in the {tool} group {toolbar}, {tool} 그룹 + In the menu bar: {path} 메뉴 막대: {path} + In the {group} group: press and hold to open it {group} 그룹: 길게 눌러 여세요 + {home}, not shown now {home}, 지금 표시되지 않음 + Tool 도구 + Command 명령 @plural {n} result|{n} results 결과 {n}개 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 결과 {n}개 중 {shown}개. 계속 입력하여 범위를 좁히세요. Recent Commands 최근 명령 @@ -5003,6 +5015,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg paste unavailable 붙여넣을 수 없습니다 @msg Save for Web: the image is empty 웹용으로 저장: 이미지가 비어 있습니다 @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: 색상 표에 색상이 하나 이상 남아 있어야 합니다 +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}`이(가) 다른 키와 같은 색상을 가리킵니다 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`은(는) "#ff8800" 같은 색상이 아닙니다 @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 색상은 최대 {MAX_TABLE}개입니다 @msg no artboard {i} (0-based; the document has {_1}) 아트보드 {i}이(가) 없습니다(0부터 시작, 문서의 아트보드 수: {_1}) @@ -5751,6 +5764,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다 @msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다 @msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다 +@msg a linked file's editing data can't be read to check it against the read roots 연결된 파일의 편집 데이터를 읽을 수 없어 읽기 루트와 대조할 수 없습니다 @msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path} @msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 @@ -7394,6 +7408,7 @@ breakText Glyphs 글리프 @msg One path lies inside the other, so they have no common tangents 한 패스가 다른 패스 안에 있어 공통 접선이 없습니다 @msg The paths overlap, so they have no internal tangents 패스가 겹쳐 있어 내부 접선이 없습니다 @msg One path lies inside the other, so they have no internal tangents 한 패스가 다른 패스 안에 있어 내부 접선이 없습니다 +@msg The point lies inside the path, so it has no tangents 점이 패스 안에 있어 접선이 없습니다 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 대시를 패스로 확장 @msg select paths with dashed strokes to expand 확장할 점선 획의 패스를 선택하십시오 @@ -9704,6 +9719,11 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Pressure Sensitive 압력 감지 + Flex Ribbon 유연한 리본 + Pulse Stroke 맥동 획 + Round Flow 둥근 흐름 + Chisel Flow 비스듬한 흐름 Fold Preview 접기 미리 보기 Fold 접기 Show Fold Lines 접는 선 표시 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e726eae41b..4b2cd0615c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3917,6 +3917,7 @@ theme Appearance Vormgeving Delete Brush Penseel verwijderen Delete Color Kleur verwijderen Restore Generated Table Gegenereerde tabel herstellen + Unshift All Colors Verschuiving van alle kleuren ongedaan maken Delete Symbol Symbool verwijderen Delete the selected symbol? Het geselecteerde symbool verwijderen? Delete the selected symbols? De geselecteerde symbolen verwijderen? @@ -4370,6 +4371,7 @@ theme Appearance Vormgeving 90° & 45° Angles Hoeken van 90° & 45° 90° Angles Hoeken van 90° Additional Plug-ins Folder Extra map met plug-ins + Plug-in Instruction Budget Instructiebudget voor plug-ins Additional Fonts Folder Extra map met lettertypen Alignment Guides Uitlijnhulplijnen Anchor Points, Handle, and Bounding Box Display Weergave van ankerpunten, greep en begrenzingskader @@ -4884,6 +4886,12 @@ font-technology Variable Variabel Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken… No commands match Geen opdrachten gevonden {pos} of {total}: {name} {pos} van {total}: {name} + No menu item Geen menu-item + Toolbar Gereedschapsbalk + {toolbar}, in the {tool} group {toolbar}, in de groep {tool} + In the menu bar: {path} In de menubalk: {path} + In the {group} group: press and hold to open it In de groep {group}: ingedrukt houden om te openen + {home}, not shown now {home}, nu niet zichtbaar @plural {n} result|{n} results {n} resultaat|{n} resultaten @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} van {n} resultaat. Typ verder om ze te beperken.|{shown} van {n} resultaten. Typ verder om ze te beperken. Recent Commands Recente opdrachten @@ -5001,6 +5009,8 @@ font-technology Variable Variabel How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Hoe dicht de aanwijzer of een gesleept punt op het scherm bij een illustratie moet komen voordat slimme hulplijnen erop uitlijnen; de afstand is bij elke zoom gelijk. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Lijnt het einde van een lijnsegment, of een cirkel getekend vanuit het middelpunt, zo uit dat het een curve in de buurt raakt. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Lijnt het einde van een lijnsegment zo uit dat het een recht segment in de buurt onder een rechte hoek raakt. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Toont op het canvas het nummer van elke slice in een vakje linksboven in de slice; staat dit uit, dan blijven de omtrekken van de slices zichtbaar. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. De kleur van de omtrekken van gebruikers- en objectslices en van hun nummervakjes; automatische slices gebruiken een vagere tint ervan. Reset all preferences to their defaults? Alle voorkeuren terugzetten naar de standaardwaarden? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. De standaardwaarden worden toegepast wanneer u in Voorkeuren op OK klikt. Annuleren daar behoudt uw huidige voorkeuren. Smaller ↔ Larger Kleiner ↔ Groter @@ -5448,6 +5458,7 @@ imageTrace Outline Contour @msg choose a location for the package kies een locatie voor het pakket @msg clipboard is empty het klembord is leeg @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: er moet ten minste één kleur in de kleurentabel blijven +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` noemt een kleur die ook een andere sleutel noemt @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` is geen kleur zoals "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maximaal {MAX_TABLE} kleuren @msg command `{0}` is not available right now: {1} opdracht `{0}` is nu niet beschikbaar: {1} @@ -6488,6 +6499,7 @@ imageTrace Outline Contour @msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots @msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots @msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots +@msg a linked file's editing data can't be read to check it against the read roots de bewerkingsgegevens van een gekoppeld bestand kunnen niet worden gelezen om ze aan de leesroots te toetsen @msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object @msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI @msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd @@ -9689,6 +9701,7 @@ breakText Glyphs Glyphs @msg One path lies inside the other, so they have no common tangents Het ene pad ligt binnen het andere, dus ze hebben geen gemeenschappelijke raaklijnen @msg The paths overlap, so they have no internal tangents De paden overlappen, dus ze hebben geen inwendige raaklijnen @msg One path lies inside the other, so they have no internal tangents Het ene pad ligt binnen het andere, dus ze hebben geen inwendige raaklijnen +@msg The point lies inside the path, so it has no tangents Het punt ligt binnen het pad, dus het heeft geen raaklijnen # 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 @@ -10140,6 +10153,11 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Pressure Sensitive Drukgevoelig + Flex Ribbon Flexibel lint + Pulse Stroke Pulserende streek + Round Flow Ronde vloei + Chisel Flow Schuine vloei Fold Preview Vouwvoorbeeld Fold Vouwen Show Fold Lines Vouwlijnen tonen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8cd18cdcb2..1ddd0a1355 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3467,6 +3467,7 @@ theme Appearance Wygląd Delete Brush Usuń pędzel Delete Color Usuń kolor Restore Generated Table Przywróć wygenerowaną tablicę + Unshift All Colors Cofnij przesunięcie wszystkich kolorów Delete Symbol Usuń symbol Delete the selected symbol? Usunąć zaznaczony symbol? Delete the selected symbols? Usunąć zaznaczone symbole? @@ -3927,6 +3928,7 @@ theme Appearance Wygląd 90° & 45° Angles Kąty 90° i 45° 90° Angles Kąty 90° Additional Plug-ins Folder Dodatkowy folder wtyczek + Plug-in Instruction Budget Budżet instrukcji wtyczek Additional Fonts Folder Dodatkowy folder czcionek Alignment Guides Linie wyrównania Anchor Points, Handle, and Bounding Box Display Wyświetlanie punktów kontrolnych, uchwytów i obwiedni @@ -4430,6 +4432,12 @@ font-technology Variable Zmienne Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów… No commands match Żadne polecenie nie pasuje {pos} of {total}: {name} {pos} z {total}: {name} + No menu item Brak pozycji menu + Toolbar Pasek narzędzi + {toolbar}, in the {tool} group {toolbar}, w grupie {tool} + In the menu bar: {path} Na pasku menu: {path} + In the {group} group: press and hold to open it W grupie {group}: naciśnij i przytrzymaj, aby ją otworzyć + {home}, not shown now {home}, teraz niewidoczne @plural {n} result|{n} results {n} wynik|{n} wyniki|{n} wyników @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} wyniku. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić. Recent Commands Ostatnie polecenia @@ -4547,6 +4555,8 @@ font-technology Variable Zmienne How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blisko na ekranie wskaźnik lub przeciągany punkt musi znaleźć się przy kompozycji, aby inteligentne linie pomocnicze go przyciągnęły; odległość jest taka sama przy każdym powiększeniu. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Przyciąga koniec odcinka lub okrąg rysowany od środka tak, aby dotykał pobliskiej krzywej. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Przyciąga koniec odcinka tak, aby spotykał pobliski prosty segment pod kątem prostym. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Pokazuje na obszarze roboczym numer każdego plasterka w ramce w jego lewym górnym rogu; po wyłączeniu kontury plasterków nadal są widoczne. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Kolor konturów plasterków użytkownika i obiektów oraz ramek z ich numerami; plasterki automatyczne używają bledszego odcienia tego koloru. Reset all preferences to their defaults? Przywrócić domyślne wartości wszystkich preferencji? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Wartości domyślne zostaną zastosowane po kliknięciu OK w Preferencjach. Anuluj w tym oknie zachowuje bieżące preferencje. Smaller ↔ Larger Mniejszy ↔ większy @@ -5197,6 +5207,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg choose a location for the package wybierz lokalizację pakietu @msg clipboard is empty schowek jest pusty @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: w tablicy kolorów musi zostać co najmniej jeden kolor +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` wskazuje kolor, który wskazuje też inny klucz @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nie jest kolorem w rodzaju "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maksymalnie {MAX_TABLE} kolorów @msg command `{0}` is not available right now: {1} polecenie `{0}` jest teraz niedostępne: {1} @@ -5836,6 +5847,7 @@ variable-list-end {0}, {1} {0} i {1} @msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu @msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu @msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu +@msg a linked file's editing data can't be read to check it against the read roots nie można odczytać danych edycji połączonego pliku, aby sprawdzić je względem katalogów głównych odczytu @msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path} @msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta @@ -7652,6 +7664,7 @@ breakText Glyphs Glify @msg One path lies inside the other, so they have no common tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają wspólnych stycznych @msg The paths overlap, so they have no internal tangents Ścieżki nachodzą na siebie, więc nie mają stycznych wewnętrznych @msg One path lies inside the other, so they have no internal tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają stycznych wewnętrznych +@msg The point lies inside the path, so it has no tangents Punkt leży wewnątrz ścieżki, więc nie ma stycznych # 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 @@ -9963,6 +9976,11 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Pressure Sensitive Czułe na nacisk + Flex Ribbon Elastyczna wstążka + Pulse Stroke Pulsujące pociągnięcie + Round Flow Okrągły ślad + Chisel Flow Skośny ślad Fold Preview Podgląd złożenia Fold Złożenie Show Fold Lines Pokaż linie zgięcia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index bba7ed642c..c054dfd3a9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -147,6 +147,7 @@ Add to Selection Adicionar à Seleção Add to Swatches Adicionar às Amostras Additional Plug-ins Folder Pasta Adicional de Plug-ins + Plug-in Instruction Budget Orçamento de Instruções de Plug-ins Additional Fonts Folder Pasta Adicional de Fontes Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes Incoming Entrada @@ -732,6 +733,7 @@ antiAlias Sharp Nítido Delete Brush Excluir Pincel Delete Color Excluir Cor Restore Generated Table Restaurar Tabela Gerada + Unshift All Colors Desfazer Mudança de Todas as Cores Delete Character Style Excluir Estilo de Caractere Delete Empty Artboards Excluir Mesas de Trabalho Vazias Delete Freeform Point Excluir Ponto Livre @@ -2727,6 +2729,8 @@ digits Malayalam Malaiala How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Quão perto na tela o ponteiro ou um ponto arrastado precisa chegar da arte para que as guias inteligentes se ajustem a ela; a distância é a mesma em qualquer zoom. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Ajusta a extremidade de um segmento de linha, ou um círculo desenhado a partir do centro, para que toque uma curva próxima. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Ajusta a extremidade de um segmento de linha para que encontre um segmento reto próximo em ângulo reto. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra na tela o número de cada fatia em uma caixa no canto superior esquerdo dela; quando desativado, os contornos das fatias continuam visíveis. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. A cor dos contornos das fatias de usuário e de objeto e das caixas com seus números; as fatias automáticas usam um tom mais apagado dessa cor. Reset all preferences to their defaults? Redefinir todas as preferências para o padrão? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Os padrões são aplicados quando você clica em OK em Preferências. Cancelar ali mantém suas preferências atuais. Restored documents open unsaved: save them to keep them. Os documentos restaurados abrem sem salvar: salve-os para mantê-los. @@ -2923,6 +2927,12 @@ digits Malayalam Malaiala Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos… No commands match Nenhum comando corresponde {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Nenhum item de menu + Toolbar Barra de Ferramentas + {toolbar}, in the {tool} group {toolbar}, no grupo {tool} + In the menu bar: {path} Na barra de menus: {path} + In the {group} group: press and hold to open it No grupo {group}: mantenha pressionado para abri-lo + {home}, not shown now {home}, não exibido agora @plural {n} result|{n} results {n} resultado|{n} resultados @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Continue digitando para filtrá-los.|{shown} de {n} resultados. Continue digitando para filtrá-los. Recent Commands Comandos recentes @@ -4344,6 +4354,7 @@ axis Both Ambos @msg choose a location for the package escolha um local para o pacote @msg clipboard is empty a área de transferência está vazia @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: pelo menos uma cor deve permanecer na tabela de cores +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` indica uma cor que outra chave também indica @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` não é uma cor como "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: no máximo {MAX_TABLE} cores @msg command `{0}` is not available right now: {1} o comando `{0}` não está disponível agora: {1} @@ -4966,6 +4977,7 @@ variable-list-end {0}, {1} {0} e {1} @msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura @msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura @msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura +@msg a linked file's editing data can't be read to check it against the read roots não é possível ler os dados de edição de um arquivo vinculado para verificá-los em relação às raízes de leitura @msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path} @msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio @@ -7816,6 +7828,7 @@ breakText Glyphs Glifos @msg One path lies inside the other, so they have no common tangents Um demarcador está dentro do outro, então eles não têm tangentes comuns @msg The paths overlap, so they have no internal tangents Os demarcadores se sobrepõem, então eles não têm tangentes internas @msg One path lies inside the other, so they have no internal tangents Um demarcador está dentro do outro, então eles não têm tangentes internas +@msg The point lies inside the path, so it has no tangents O ponto está dentro do demarcador, então ele não tem tangentes # 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 @@ -10174,6 +10187,11 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Pressure Sensitive Sensível à pressão + Flex Ribbon Fita flexível + Pulse Stroke Traço pulsante + Round Flow Fluxo redondo + Chisel Flow Fluxo chanfrado Fold Preview Visualização da Dobra Fold Dobra Show Fold Lines Mostrar Linhas de Dobra diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e2ab3a9097..5a59fc7243 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -139,6 +139,7 @@ Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета Additional Plug-ins Folder Папка дополнительных модулей + Plug-in Instruction Budget Бюджет инструкций модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины Incoming Входящая @@ -816,6 +817,7 @@ font-technology Variable Вариативные Delete Brush Удалить кисть Delete Color Удалить цвет Restore Generated Table Восстановить созданную таблицу + Unshift All Colors Отменить сдвиг всех цветов Delete Character Style Удалить стиль символа Delete Empty Artboards Удалить пустые монтажные области Delete Freeform Point Удалить произвольную точку @@ -3272,6 +3274,8 @@ digits Malayalam Малаялам How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Насколько близко на экране указатель или перетаскиваемая точка должны подойти к объекту, чтобы умные направляющие привязали их; расстояние одинаково при любом масштабе. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Привязывает конец отрезка или окружность, нарисованную от центра, так, чтобы она касалась ближайшей кривой. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Привязывает конец отрезка так, чтобы он встречал ближайший прямой сегмент под прямым углом. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показывает на холсте номер каждого фрагмента в рамке в его левом верхнем углу; если параметр выключен, контуры фрагментов по-прежнему видны. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Цвет контуров пользовательских и объектных фрагментов и рамок с их номерами; автоматические фрагменты используют более бледный оттенок этого цвета. Reset all preferences to their defaults? Сбросить все настройки до значений по умолчанию? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значения по умолчанию применяются, когда вы нажимаете ОК в окне «Настройки». Отмена там сохраняет текущие настройки. Restore Recovered Documents Восстановить восстановленные документы @@ -3503,6 +3507,12 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов… No commands match Нет подходящих команд {pos} of {total}: {name} {pos} из {total}: {name} + No menu item Нет пункта меню + Toolbar Панель инструментов + {toolbar}, in the {tool} group {toolbar}, в группе «{tool}» + In the menu bar: {path} В строке меню: {path} + In the {group} group: press and hold to open it В группе {group}: нажмите и удерживайте, чтобы открыть её + {home}, not shown now {home}, сейчас не показано @plural {n} result|{n} results {n} результат|{n} результата|{n} результатов @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} из {n} результата. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их. Recent Commands Недавние команды @@ -5108,6 +5118,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg choose a location for the package выберите расположение для пакета @msg clipboard is empty буфер обмена пуст @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: в цветовой таблице должен остаться хотя бы один цвет +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` обозначает цвет, который обозначает и другой ключ @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не является цветом, например "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: не более {MAX_TABLE} цветов @msg command `{0}` is not available right now: {1} команда `{0}` сейчас недоступна: {1} @@ -5775,6 +5786,7 @@ variable-list-end {0}, {1} {0} и {1} @msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения @msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения @msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения +@msg a linked file's editing data can't be read to check it against the read roots не удаётся прочитать данные редактирования связанного файла, чтобы сверить их с корневыми папками для чтения @msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path} @msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст @@ -7787,6 +7799,7 @@ breakText Glyphs Глифы @msg One path lies inside the other, so they have no common tangents Один контур лежит внутри другого, поэтому у них нет общих касательных @msg The paths overlap, so they have no internal tangents Контуры перекрываются, поэтому у них нет внутренних касательных @msg One path lies inside the other, so they have no internal tangents Один контур лежит внутри другого, поэтому у них нет внутренних касательных +@msg The point lies inside the path, so it has no tangents Точка лежит внутри контура, поэтому у неё нет касательных # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разобрать штрихи на контуры @msg select paths with dashed strokes to expand выделите контуры со штриховой обводкой для разбора @@ -10201,3 +10214,8 @@ shape Open Открытый @msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Pressure Sensitive Чувствительные к нажиму + Flex Ribbon Гибкая лента + Pulse Stroke Пульсирующий штрих + Round Flow Круглый поток + Chisel Flow Косой поток diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4893ecc8ce..40b2085ae4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -129,6 +129,7 @@ Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger Additional Plug-ins Folder Mapp för ytterligare plugins + Plug-in Instruction Budget Instruktionsbudget för plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter Incoming Inkommande @@ -806,6 +807,7 @@ font-technology Variable Variabla Delete Brush Radera pensel Delete Color Radera färg Restore Generated Table Återställ genererad tabell + Unshift All Colors Ta bort förskjutning av alla färger Delete Character Style Radera teckenstil Delete Empty Artboards Radera tomma ritytor Delete Freeform Point Radera fri punkt @@ -3166,6 +3168,8 @@ digits Malayalam Malayalam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Hur nära på skärmen pekaren eller en dragen punkt måste komma teckningen för att de smarta stödlinjerna ska fästa mot den; avståndet är detsamma vid alla zoomnivåer. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Fäster änden av ett linjesegment, eller en cirkel ritad från sin mitt, så att den rör en närliggande kurva. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Fäster änden av ett linjesegment så att det möter ett närliggande rakt segment i rät vinkel. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Visar varje skivas nummer i en ruta i dess övre vänstra hörn på arbetsytan; när det är avstängt visas skivornas konturer fortfarande. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Färgen på konturerna för användar- och objektskivor och på deras nummerrutor; automatiska skivor använder en blekare nyans av den. Reset all preferences to their defaults? Återställa alla inställningar till standard? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardvärdena verkställs när du klickar på OK i Inställningar. Avbryt där behåller dina nuvarande inställningar. Restore Recovered Documents Återställ återskapade dokument @@ -3383,6 +3387,12 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter… No commands match Inga kommandon matchar {pos} of {total}: {name} {pos} av {total}: {name} + No menu item Inget menyalternativ + Toolbar Verktygsfält + {toolbar}, in the {tool} group {toolbar}, i gruppen {tool} + In the menu bar: {path} I menyraden: {path} + In the {group} group: press and hold to open it I gruppen {group}: tryck och håll ned för att öppna den + {home}, not shown now {home}, visas inte nu @plural {n} result|{n} results {n} resultat|{n} resultat @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} av {n} resultat. Fortsätt skriva för att begränsa dem.|{shown} av {n} resultat. Fortsätt skriva för att begränsa dem. Recent Commands Senaste kommandon @@ -4977,6 +4987,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg choose a location for the package välj en plats för paketet @msg clipboard is empty urklippet är tomt @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: minst en färg måste finnas kvar i färgtabellen +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` anger en färg som även en annan nyckel anger @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` är inte en färg som "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: högst {MAX_TABLE} färger @msg command `{0}` is not available right now: {1} kommandot `{0}` är inte tillgängligt just nu: {1} @@ -5653,6 +5664,7 @@ variable-list-end {0}, {1} {0} och {1} @msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path} @msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna @msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdata för en länkad fil kan inte läsas för att kontrolleras mot läsrötterna @msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path} @msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom @@ -7831,6 +7843,7 @@ breakText Glyphs Glyfer @msg One path lies inside the other, so they have no common tangents Den ena banan ligger inuti den andra, så de har inga gemensamma tangenter @msg The paths overlap, so they have no internal tangents Banorna överlappar, så de har inga inre tangenter @msg One path lies inside the other, so they have no internal tangents Den ena banan ligger inuti den andra, så de har inga inre tangenter +@msg The point lies inside the path, so it has no tangents Punkten ligger inuti banan, så den har inga tangenter # 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 @@ -9803,3 +9816,8 @@ digits Hindi Hindi @msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. @msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Pressure Sensitive Tryckkänslig + Flex Ribbon Flexibelt band + Pulse Stroke Pulserande drag + Round Flow Runt flöde + Chisel Flow Snedflöde diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index be56dca076..79ba20d44b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -595,8 +595,9 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { .flat_map(|(_, lib)| lib.brushes.iter().map(|b| b.name.clone()).collect::>()) .collect(); names.sort(); + let duplicates: Vec<&str> = names.windows(2).filter(|pair| pair[0] == pair[1]).map(|pair| pair[0].as_str()).collect(); + assert_eq!(duplicates, ["Zigzag"], "only the established Pattern Borders / Game Trails name is shared"); names.dedup(); - assert_eq!(names.len(), 46, "{names:?}"); let mut bad = vec![]; for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { let missing: Vec<&String> = names.iter().filter(|n| lang.catalog().plain(n).is_none()).collect(); @@ -804,6 +805,21 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() { } } +/// Each row in the `search` context, which adds a language's words to a group of words with the same +/// meaning for the command palette, names a group and adds single words of no other group. No +/// catalog has to have these rows. +#[test] +fn search_rows_name_a_group_and_add_single_words() { + let mut bad = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + for (_, src, tr) in entries.iter().filter(|(ctx, _, _)| ctx == crate::palette::words::CONTEXT) { + bad.extend(crate::palette::words::row_problems(src, tr).into_iter().map(|p| format!("{}: {p}", l.code))); + } + } + assert!(bad.is_empty(), "{bad:#?}"); +} + /// The Painted and Sketched graphic style library's name and its styles' names have a row in every /// bundled catalog. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3f6be1e0f9..b6b9a97705 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -126,6 +126,7 @@ Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle Additional Plug-ins Folder Ek Eklentiler Klasörü + Plug-in Instruction Budget Eklenti Talimat Bütçesi Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın Incoming Gelen @@ -797,6 +798,7 @@ font-technology Variable Değişken Delete Brush Fırçayı Sil Delete Color Rengi Sil Restore Generated Table Oluşturulan Tabloyu Geri Yükle + Unshift All Colors Tüm Renklerin Kaydırmasını Kaldır Delete Character Style Karakter Stilini Sil Delete Empty Artboards Boş Çalışma Yüzeylerini Sil Delete Freeform Point Serbest Biçim Noktasını Sil @@ -3009,6 +3011,8 @@ digits Malayalam Malayalam How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Akıllı Kılavuzların yaslaması için işaretçinin veya sürüklenen noktanın ekranda çizime ne kadar yaklaşması gerektiği; mesafe her yakınlaştırmada aynıdır. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Bir çizgi parçasının ucunu veya merkezinden çizilen bir daireyi yakındaki bir eğriye değecek şekilde yaslar. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Bir çizgi parçasının ucunu yakındaki düz bir parçayla dik açıyla buluşacak şekilde yaslar. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Tuvalde her dilimin numarasını sol üst köşesindeki bir kutuda gösterir; kapalıyken dilimlerin dış çizgileri görünmeye devam eder. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Kullanıcı ve nesne dilimlerinin dış çizgilerinin ve numara kutularının rengi; otomatik dilimler bu rengin daha soluk bir tonunu kullanır. Reset all preferences to their defaults? Tüm tercihler varsayılanlarına sıfırlansın mı? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Varsayılanlar, Tercihler'de Tamam'a tıkladığınızda uygulanır. Oradaki İptal, mevcut tercihlerinizi korur. Restore Recovered Documents Kurtarılan Belgeleri Geri Yükle @@ -3261,6 +3265,12 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın… No commands match Eşleşen komut yok {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Menü öğesi yok + Toolbar Araç Çubuğu + {toolbar}, in the {tool} group {toolbar}, {tool} grubunda + In the menu bar: {path} Menü çubuğunda: {path} + In the {group} group: press and hold to open it {group} grubunda: açmak için basılı tutun + {home}, not shown now {home}, şu anda gösterilmiyor @plural {n} result|{n} results {n} sonuç @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} sonuçtan {shown} tanesi. Daraltmak için yazmaya devam edin. Recent Commands Son komutlar @@ -4794,6 +4804,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg choose a location for the package paket için bir yer seçin @msg clipboard is empty pano boş @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: renk tablosunda en az bir renk kalmalı +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` başka bir anahtarın da belirttiği bir rengi belirtiyor @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" gibi bir renk değil @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: en fazla {MAX_TABLE} renginde @msg command `{0}` is not available right now: {1} `{0}` komutu şu anda kullanılamıyor: {1} @@ -7598,6 +7609,7 @@ axis Y Axis Y ekseni @msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında @msg a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında @msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında +@msg a linked file's editing data can't be read to check it against the read roots bağlantılı bir dosyanın düzenleme verileri okuma köklerine göre denetlemek için okunamıyor @msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla @msg the method needs an XML value yöntem için bir XML değeri gerekir @msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) boya bir serbest biçimli degrade değil (paint.editGradient {{kind: "freeform"}} ile bir tane uygulayın) @@ -9687,6 +9699,7 @@ breakText Glyphs Glifler @msg One path lies inside the other, so they have no common tangents Bir yol diğerinin içinde, bu yüzden ortak teğetleri yok @msg The paths overlap, so they have no internal tangents Yollar örtüşüyor, bu yüzden iç teğetleri yok @msg One path lies inside the other, so they have no internal tangents Bir yol diğerinin içinde, bu yüzden iç teğetleri yok +@msg The point lies inside the path, so it has no tangents Nokta yolun içinde, bu yüzden teğeti yok # 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 @@ -10061,6 +10074,11 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Pressure Sensitive Basınca Duyarlı + Flex Ribbon Esnek Şerit + Pulse Stroke Atımlı Çizgi + Round Flow Yuvarlak Akış + Chisel Flow Eğimli Akış Fold Preview Katlama Önizlemesi Fold Katlama Show Fold Lines Katlama Çizgilerini Göster diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 845010a40f..3ce4ecf5a1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -135,6 +135,7 @@ Add to Swatches Додати до зразків Add Used Colors Додати використані кольори Additional Plug-ins Folder Папка додаткових модулів + Plug-in Instruction Budget Бюджет інструкцій модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини Incoming Вхідна @@ -814,6 +815,7 @@ font-technology Variable Варіативні Delete Brush Видалити пензель Delete Color Видалити колір Restore Generated Table Відновити створену таблицю + Unshift All Colors Скасувати зсув усіх кольорів Delete Character Style Видалити стиль символу Delete Empty Artboards Видалити порожні монтажні області Delete Freeform Point Видалити довільну точку @@ -3282,6 +3284,8 @@ digits Malayalam Малаялам How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Наскільки близько на екрані вказівник або перетягувана точка мають підійти до об’єкта, щоб розумні напрямні їх прив’язали; відстань однакова за будь-якого масштабу. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Прив’язує кінець відрізка або коло, намальоване від центру, так, щоб воно торкалося найближчої кривої. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Прив’язує кінець відрізка так, щоб він зустрічав найближчий прямий сегмент під прямим кутом. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показує на полотні номер кожного фрагмента в рамці в його лівому верхньому куті; коли параметр вимкнено, контури фрагментів і далі видно. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Колір контурів користувацьких і об’єктних фрагментів та рамок з їхніми номерами; автоматичні фрагменти використовують блідіший відтінок цього кольору. Reset all preferences to their defaults? Скинути всі налаштування до значень за промовчанням? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значення за промовчанням застосовуються, коли ви натискаєте ОК у вікні «Налаштування». Скасувати там зберігає поточні налаштування. Restore Recovered Documents Відновити відновлені документи @@ -3513,6 +3517,14 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів… No commands match Немає відповідних команд {pos} of {total}: {name} {pos} з {total}: {name} + No menu item Немає пункту меню + Toolbar Панель інструментів + {toolbar}, in the {tool} group {toolbar}, у групі «{tool}» + In the menu bar: {path} У рядку меню: {path} + In the {group} group: press and hold to open it У групі {group}: натисніть і утримуйте, щоб відкрити її + {home}, not shown now {home}, зараз не показано + Tool Інструмент + Command Команда @plural {n} result|{n} results {n} результат|{n} результати|{n} результатів @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} з {n} результату. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх. Recent Commands Нещодавні команди @@ -5095,6 +5107,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg choose a location for the package виберіть розташування для пакета @msg clipboard is empty буфер обміну порожній @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: у колірній таблиці має залишитися принаймні один колір +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` позначає колір, який позначає й інший ключ @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не є кольором, наприклад "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: не більше {MAX_TABLE} кольорів @msg command `{0}` is not available right now: {1} команда `{0}` зараз недоступна: {1} @@ -5758,6 +5771,7 @@ variable-list-end {0}, {1} {0} і {1} @msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання @msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання @msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання +@msg a linked file's editing data can't be read to check it against the read roots не вдається прочитати дані редагування зв’язаного файлу, щоб звірити їх із кореневими папками для читання @msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path} @msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній @@ -7404,6 +7418,7 @@ breakText Glyphs Гліфи @msg One path lies inside the other, so they have no common tangents Один контур лежить усередині іншого, тому вони не мають спільних дотичних @msg The paths overlap, so they have no internal tangents Контури перекриваються, тому вони не мають внутрішніх дотичних @msg One path lies inside the other, so they have no internal tangents Один контур лежить усередині іншого, тому вони не мають внутрішніх дотичних +@msg The point lies inside the path, so it has no tangents Точка лежить усередині контуру, тому вона не має дотичних # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Розібрати штрихи на контури @msg select paths with dashed strokes to expand виділіть контури зі штриховим обведенням для розбору @@ -9716,6 +9731,11 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Pressure Sensitive Чутливі до натиску + Flex Ribbon Гнучка стрічка + Pulse Stroke Пульсуючий штрих + Round Flow Круглий потік + Chisel Flow Косий потік Fold Preview Перегляд згину Fold Згин Show Fold Lines Показати лінії згину diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d501f87e17..29dce22126 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -157,6 +157,7 @@ Add Used Colors Thêm các màu đã dùng Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung + Plug-in Instruction Budget Ngân sách lệnh của plug-in Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau Incoming Phía vào Outgoing Phía ra @@ -944,6 +945,7 @@ font-technology Variable Biến thiên Delete Brush Xóa cọ Delete Color Xóa màu Restore Generated Table Khôi phục bảng đã tạo + Unshift All Colors Bỏ dịch chuyển tất cả màu Delete Character Style Xóa kiểu ký tự Delete Data Set Xóa tập dữ liệu Delete Design Xóa thiết kế @@ -3598,6 +3600,8 @@ mark-style Japanese Kiểu Nhật How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Con trỏ hoặc điểm đang kéo phải đến gần hình vẽ trên màn hình bao nhiêu để đường căn thông minh hút vào; khoảng cách này như nhau ở mọi mức thu phóng. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Hút đầu mút của đoạn thẳng, hoặc hình tròn vẽ từ tâm, để nó chạm vào một đường cong ở gần. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Hút đầu mút của đoạn thẳng để nó gặp một đoạn thẳng ở gần theo góc vuông. + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Hiển thị trên khung vẽ số của mỗi lát cắt trong một ô ở góc trên bên trái của nó; khi tắt, đường viền của các lát cắt vẫn hiện. + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Màu của đường viền lát cắt người dùng và lát cắt đối tượng cùng các ô số của chúng; lát cắt tự động dùng một sắc độ nhạt hơn của màu này. Reset all preferences to their defaults? Đặt lại tất cả tùy chọn về mặc định? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Giá trị mặc định được áp dụng khi bạn nhấn OK trong Tùy chọn. Hủy ở đó giữ nguyên các tùy chọn hiện tại của bạn. Restore Recovered Documents Khôi phục tài liệu đã phục hồi @@ -3859,6 +3863,14 @@ mark-style Japanese Kiểu Nhật Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng… No commands match Không có lệnh nào khớp {pos} of {total}: {name} {pos} trên {total}: {name} + No menu item Không có mục menu + Toolbar Thanh công cụ + {toolbar}, in the {tool} group {toolbar}, trong nhóm {tool} + In the menu bar: {path} Trên thanh menu: {path} + In the {group} group: press and hold to open it Trong nhóm {group}: nhấn giữ để mở + {home}, not shown now {home}, hiện không hiển thị + Tool Công cụ + Command Lệnh @plural {n} result|{n} results {n} kết quả @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} trên {n} kết quả. Tiếp tục gõ để thu hẹp. Recent Commands Lệnh gần đây @@ -5063,6 +5075,7 @@ theme Appearance Giao diện @msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc @msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc @msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's editing data can't be read to check it against the read roots không thể đọc dữ liệu chỉnh sửa của một tệp được liên kết để kiểm tra với các thư mục gốc đọc @msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc @msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết @msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path} @@ -5115,6 +5128,7 @@ theme Appearance Giao diện @msg clipboard is empty khay nhớ tạm trống @msg closing needs three anchors đóng đường dẫn cần ba điểm neo @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: phải giữ lại ít nhất một màu trong bảng màu +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted: `{k}` chỉ một màu mà khóa khác cũng chỉ @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` không phải là màu như "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: tối đa {MAX_TABLE} màu @msg column must be true or a number from 1 column phải là true hoặc số từ 1 @@ -7448,6 +7462,7 @@ breakText Glyphs Glyph @msg One path lies inside the other, so they have no common tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến chung @msg The paths overlap, so they have no internal tangents Các đường dẫn chồng lên nhau, nên chúng không có tiếp tuyến trong @msg One path lies inside the other, so they have no internal tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến trong +@msg The point lies inside the path, so it has no tangents Điểm nằm bên trong đường dẫn, nên nó không có tiếp tuyến # 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 @@ -7955,4 +7970,9 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Pressure Sensitive Nhạy áp lực + Flex Ribbon Dải mềm + Pulse Stroke Nét rung + Round Flow Nét tròn + Chisel Flow Nét vát @msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: hãy dùng "{_1}" hoặc "{_2}" diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a0ffedd15c..d4a957a4b8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -90,6 +90,7 @@ Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 Additional Plug-ins Folder 附加增效工具文件夹 + Plug-in Instruction Budget 增效工具指令预算 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 Incoming 入侧 @@ -762,6 +763,7 @@ antiAlias Sharp 锐利 Delete Brush 删除画笔 Delete Color 删除颜色 Restore Generated Table 恢复生成的颜色表 + Unshift All Colors 取消偏移所有颜色 Delete Character Style 删除字符样式 Delete Empty Artboards 删除空白画板 Delete Freeform Point 删除自由点 @@ -3139,6 +3141,8 @@ digits Malayalam 马拉雅拉姆数字 How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. 指针或拖动的点在屏幕上需离图稿多近,智能参考线才会吸附;该距离在任何缩放比例下都相同。 Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 吸附线段的端点或从中心绘制的圆,使其与附近的曲线相切。 Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 吸附线段的端点,使其与附近的直线段成直角相交。 + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 在画布上于每个切片左上角的方框中显示其编号;关闭时,切片轮廓仍会显示。 + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 用户切片和对象切片的轮廓及其编号方框的颜色;自动切片使用此颜色较淡的色调。 Reset all preferences to their defaults? 将所有首选项重置为默认值? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 在首选项中点击确定后才会应用默认值。在那里点击取消会保留当前首选项。 Restore Recovered Documents 恢复已恢复的文档 @@ -3338,6 +3342,12 @@ digits Malayalam 马拉雅拉姆数字 Search commands, tools, panels and effects… 搜索命令、工具、面板和效果… No commands match 没有匹配的命令 {pos} of {total}: {name} 第 {pos} 个,共 {total} 个:{name} + No menu item 无菜单项 + Toolbar 工具栏 + {toolbar}, in the {tool} group {toolbar},位于 {tool} 组中 + In the menu bar: {path} 在菜单栏中:{path} + In the {group} group: press and hold to open it 在“{group}”组中:按住即可打开 + {home}, not shown now {home},当前未显示 @plural {n} result|{n} results {n} 个结果 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 个结果,显示 {shown} 个。继续输入以缩小范围。 Recent Commands 最近使用的命令 @@ -4765,6 +4775,7 @@ imageTrace Outline 轮廓 @msg paste unavailable 无法粘贴 @msg Save for Web: the image is empty 存储为 Web 所用格式:图像为空 @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted:颜色表中至少要保留一种颜色 +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted:`{k}` 与另一个键指的是同一种颜色 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}:`{h}` 不是颜色,例如 "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}:最多 {MAX_TABLE} 种颜色 @msg no artboard {i} (0-based; the document has {_1}) 没有画板 {i} (从 0 开始计数;文档有 {_1} 个) @@ -5487,6 +5498,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外 @msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外 @msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外 +@msg a linked file's editing data can't be read to check it against the read roots 无法读取链接文件的编辑数据,因此无法对照读取根目录进行检查 @msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒绝自动化路径:路径为空 @@ -7634,6 +7646,7 @@ breakText Glyphs 字形 @msg One path lies inside the other, so they have no common tangents 一条路径位于另一条之内,因此它们没有公切线 @msg The paths overlap, so they have no internal tangents 路径相互重叠,因此它们没有内公切线 @msg One path lies inside the other, so they have no internal tangents 一条路径位于另一条之内,因此它们没有内公切线 +@msg The point lies inside the path, so it has no tangents 该点位于路径之内,因此没有切线 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 将短划线扩展为路径 @msg select paths with dashed strokes to expand 请选择要扩展的虚线描边路径 @@ -9956,3 +9969,8 @@ breakText Glyphs 字形 @msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 @msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Pressure Sensitive 压感画笔 + Flex Ribbon 柔韧色带 + Pulse Stroke 脉动笔触 + Round Flow 圆头流线 + Chisel Flow 斜头流线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 86a856ddde..5cfacaca19 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -99,6 +99,7 @@ Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 Additional Plug-ins Folder 額外的增效模組資料夾 + Plug-in Instruction Budget 增效模組指令預算 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 Incoming 入側 @@ -782,6 +783,7 @@ font-technology Variable 可變 Delete Brush 刪除筆刷 Delete Color 刪除顏色 Restore Generated Table 還原產生的色彩表 + Unshift All Colors 取消位移所有顏色 Delete Character Style 刪除字元樣式 Delete Empty Artboards 刪除空白工作區域 Delete Freeform Point 刪除任意形狀錨點 @@ -2234,6 +2236,7 @@ file-filter Templates 範本 @msg paste unavailable 無法貼上 @msg Save for Web: the image is empty 儲存為網頁用:影像是空的 @msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted:色彩表中至少要保留一種顏色 +@msg colorTable.shifted: `{k}` names a color another key names colorTable.shifted:`{k}` 與另一個鍵指的是同一種顏色 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}:`{h}` 不是像 "#ff8800" 這樣的顏色 @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}:最多 {MAX_TABLE} 種顏色 @msg no artboard {i} (0-based; the document has {_1}) 沒有工作區域 {i} (從 0 起算;文件有 {_1} 個) @@ -2960,6 +2963,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外 @msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外 @msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外 +@msg a linked file's editing data can't be read to check it against the read roots 無法讀取連結檔案的編輯資料,因此無法對照讀取根目錄進行檢查 @msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的 @@ -4486,6 +4490,8 @@ digits Malayalam 馬來亞拉姆數字 How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. 指標或拖曳的點在螢幕上需離圖稿多近,智慧型參考線才會靠齊;此距離在任何縮放比例下都相同。 Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. 靠齊線段的端點或從中心繪製的圓,使其與附近的曲線相切。 Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. 靠齊線段的端點,使其與附近的直線段成直角相交。 + Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 在畫布上於每個切片左上角的方框中顯示其編號;關閉時,切片輪廓仍會顯示。 + The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 使用者切片和物件切片的輪廓及其編號方框的顏色;自動切片使用此顏色較淡的色調。 Reset all preferences to their defaults? 要將所有偏好設定重設為預設值嗎? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 在偏好設定中按下確定後才會套用預設值。在那裡按下取消會保留目前的偏好設定。 Restore Recovered Documents 還原找回的文件 @@ -4715,6 +4721,14 @@ digits Malayalam 馬來亞拉姆數字 Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果… No commands match 沒有符合的指令 {pos} of {total}: {name} 第 {pos} 個,共 {total} 個:{name} + No menu item 無選單項目 + Toolbar 工具列 + {toolbar}, in the {tool} group {toolbar},位於 {tool} 群組中 + In the menu bar: {path} 在選單列中:{path} + In the {group} group: press and hold to open it 在「{group}」群組中:按住即可開啟 + {home}, not shown now {home},目前未顯示 + Tool 工具 + Command 指令 @plural {n} result|{n} results {n} 個結果 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 個結果,顯示 {shown} 個。繼續輸入以縮小範圍。 Recent Commands 最近使用的指令 @@ -7453,6 +7467,7 @@ breakText Glyphs 字符 @msg One path lies inside the other, so they have no common tangents 一條路徑位於另一條之內,因此它們沒有公切線 @msg The paths overlap, so they have no internal tangents 路徑互相重疊,因此它們沒有內公切線 @msg One path lies inside the other, so they have no internal tangents 一條路徑位於另一條之內,因此它們沒有內公切線 +@msg The point lies inside the path, so it has no tangents 該點位於路徑之內,因此沒有切線 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 將短破折號展開為路徑 @msg select paths with dashed strokes to expand 請選取要展開的虛線筆畫路徑 @@ -9768,3 +9783,8 @@ breakText Glyphs 字符 @msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 @msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Pressure Sensitive 壓感筆刷 + Flex Ribbon 柔韌色帶 + Pulse Stroke 脈動筆觸 + Round Flow 圓頭流線 + Chisel Flow 斜頭流線 diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index 7694791af9..10e0f6ed13 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -37,6 +37,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { for (title, items) in tree.iter() { let text = egui::RichText::new(tl!(title)).size(13.0).color(t.text); let resp = ui.add(egui::Button::new(text)); + crate::palette::note_spot(ui, resp.rect, || crate::palette::SpotAt::Menu((*title).to_string())); egui::Popup::menu(&resp).show(|ui| menu_body(app, ui, items, &mut clicked)); if *title == "File" { file_open = egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&resp)); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ad85ed5bfa..d5ec92b934 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -795,10 +795,17 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option edit.unwrap_or(false), Err(e) => return Some(Err(e)), }; + let keep_art = match opt_bool(p, "keepArt") { + Ok(keep) => keep.unwrap_or(false), + Err(e) => return Some(Err(e)), + }; if edit || name.is_some() { + if keep_art { + return Some(Err("`keepArt` applies only to a new symbol".into())); + } crate::dialogs::symbol_options::open_edit(app, name.as_deref()) } else { - crate::dialogs::symbol_options::open(app) + crate::dialogs::symbol_options::open(app, keep_art) } } "ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 137c3b5758..f4bf3ff9a8 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -707,6 +707,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { panel("Pathfinder", "pathfinder"), panel("Pattern Options", "patternOptions"), panel("Properties", "properties"), + panel("Production Preflight", crate::panels::preflight::ID), panel("Script Console", crate::panels::script_console::ID), panel("Separations Preview", "separations"), panel("Stroke", "stroke"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e2c40562f1..e8b5eddf5b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -689,7 +689,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -1027,7 +1027,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 6122e7357b..86c50ae2ea 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -9,6 +9,7 @@ use crate::theme::Tokens; use crate::{VectorcraftApp, menus}; mod search; +pub(crate) mod words; /// Engine commands the palette leaves out, each with the UI command of the same name that runs it /// the way the panels and menus do: (engine id, UI command id). The Layers panel's Delete @@ -268,6 +269,28 @@ fn shown_label(lang: crate::i18n::Lang, label: &str) -> String { label.split(" › ").map(|s| crate::i18n::tr(lang, s)).collect::>().join(" › ") } +/// The label of the item of the menu bar that runs `e`, in `lang`, as the menu bar draws it +/// ([`menus::display_label`]). A built-in effect's item translates by its effect id first, as the +/// Effect menu's does. Any other item translates by the id of the command it runs first (File › +/// Close is Cerrar archivo in Spanish), and a name the menu shows as written ([`menus::shows_a_name`]: +/// a filter or live-effect plug-in's) does not translate. +fn item_label(lang: crate::i18n::Lang, e: &Entry) -> &'static str { + if let Some(effect) = e.id.strip_prefix("effect:") { + return match vectorcraft_plugins::effect::plugin_id(effect) { + Some(_) => e.menu_item, + None => crate::i18n::tr_id(lang, effect, e.menu_item), + }; + } + // The command the menu item runs: `plugin.dialog` for a filter, `window.panel` for a panel and + // the engine command a UI command wraps. + let id = match e.id.as_str() { + id if id.starts_with("plugin:") => "plugin.dialog", + id if id.starts_with("panel:") => "window.panel", + id => WRAPPED.iter().find(|(_, ui)| *ui == id).map_or(id, |(engine, _)| engine), + }; + if menus::shows_a_name(id, e.menu_item) { e.menu_item } else { crate::i18n::tr_id(lang, id, e.menu_item) } +} + /// One palette entry, with what it shows and what a query matches worked out once. pub(crate) struct Entry { id: String, @@ -286,6 +309,12 @@ pub(crate) struct Entry { menu_item: &'static str, /// The entry's kind, in the order [`search::kind`] ranks kinds. kind: u8, + /// Where the row's label starts in `shown`: after the menu path, which the row shows as the + /// entry's home instead ([`home_text`]), or 0. + label_at: usize, + /// Does the row's home name the item of the menu bar after its menu path, since the item's + /// label differs from the entry's? + names_item: bool, } /// The palette's entries, the index a query is looked up in, and the last query's ranked results. @@ -337,11 +366,28 @@ fn entries_in(ctx: &egui::Context, lang: crate::i18n::Lang, native: bool) -> Arc fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { let list = build_in(lang, native); let shown_homes: Vec> = - list.iter().map(|e| e.home.as_deref().map(|h| format!("{} › {}", shown_label(lang, h), crate::i18n::tr(lang, e.menu_item)))).collect(); - let index = search::Index::build(&list, &shown_homes); + list.iter().map(|e| e.home.as_deref().map(|h| format!("{} › {}", shown_label(lang, h), item_label(lang, e)))).collect(); + // A group's row in the `search` context gives its words in `lang`; a plain row is not read. + let search_row = |key: &str| crate::i18n::tr_ctx_row(lang, words::CONTEXT, key).map(str::to_string); + let index = search::Index::build(&list, &shown_homes, ¶ms_texts(&list), search_row); Catalog { list, index, ranked: std::sync::Mutex::new(None) } } +/// The params text of each entry's command, which the index reads a description from +/// ([`search::description`]): an engine or plug-in command's, a UI command's (the one it wraps +/// keeps its own) and an effect's. A tool, a panel and a filter plug-in have none. +fn params_texts(list: &[Entry]) -> Vec<&'static str> { + let engine = vectorcraft_engine::command_specs().iter().chain(vectorcraft_engine::cmd::plugin::command_specs()); + let mut by_id: std::collections::HashMap<&str, &'static str> = engine.map(|c| (c.id, c.params)).collect(); + by_id.extend(menus::UI_COMMANDS.iter().map(|c| (c.0, c.3))); + list.iter() + .map(|e| match e.id.strip_prefix("effect:") { + Some(effect) => vectorcraft_effects::effect_info(effect).map_or("", |info| info.params), + None => by_id.get(e.id.as_str()).copied().unwrap_or(""), + }) + .collect() +} + /// The palette's entries in `lang` with the in-window menu bar. #[cfg(test)] fn build(lang: crate::i18n::Lang) -> Vec { @@ -374,7 +420,16 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { } let (home, menu_item) = homes.get(&d.id).map_or((None, ""), |(path, item)| (Some(path.clone()), *item)); let kind = search::kind(&d.id, home.as_deref()); - Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind } + // A row with a home shows its label without the menu path in front of it. A path that + // makes the name distinct ([`distinct_names`]) stays, unless the row's home shows that + // same path or it is the Tools in front of a tool's name, which the tool's kind and + // toolbar show. + let tool = d.id.starts_with("tool:"); + let drop = if d.in_context { home.as_deref() == Some(d.path.as_str()) || (tool && d.path == "Tools") } else { home.is_some() || tool }; + let prefix = format!("{} › ", shown_label(lang, &d.path)); + let label_at = if drop && !d.path.is_empty() && shown.starts_with(&prefix) { prefix.len() } else { 0 }; + let names_item = !menu_item.is_empty() && menu_item != d.label; + Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind, label_at, names_item } }) .collect() } @@ -445,10 +500,365 @@ const TOP: f32 = 90.0; /// The space kept between the popup and the bottom of the window, in points. const BOTTOM_GAP: f32 = 8.0; -/// What a result row shows and screen readers read: its name, and its shortcut after a comma. -fn row_label(e: &Entry) -> String { +/// The point size of the kind icon at the start of a result row. +const KIND_ICON: f32 = 14.0; +/// The point size of the home's text after a row's label. +const HOME_TEXT: f32 = 11.0; + +/// The kind of result `e` is: the icon its row starts with and the word screen readers read +/// first, in the UI language. A tool shows its own icon. +fn kind_of(e: &Entry) -> (&'static str, &'static str) { + match e.id.split_once(':') { + Some(("tool", tool)) => (vectorcraft_tools::tool_info(tool).map_or("square-dashed", |t| crate::icons::tool_icon(t.icon)), tl!("Tool")), + Some(("panel", _)) => ("layout-grid", tl!("Panel")), + Some(("effect", _)) => ("dc-fx", tl!("Effect")), + Some(("plugin", _)) => ("dc-filter", tl!("Filter")), + _ => ("menu", tl!("Command")), + } +} + +/// The label a result row shows: its name without the menu path its home shows. +fn label_of(e: &Entry) -> &str { + e.shown.get(e.label_at..).unwrap_or(&e.shown) +} + +/// Where result `e` lives, as its row shows it: a tool's place on the toolbars ([`tool_home`]), +/// the menu path of the item of the menu bar that runs it (with the item's label when it differs +/// from the result's), or "No menu item". +fn home_text(app: &VectorcraftApp, e: &Entry) -> String { + let lang = crate::i18n::current(); + if let Some(tool) = e.id.strip_prefix("tool:") { + return tool_home(app, tool); + } + match &e.home { + Some(path) if e.names_item => format!("{} › {}", shown_label(lang, path), item_label(lang, e)), + Some(path) => shown_label(lang, path), + None => tl!("No menu item").to_string(), + } +} + +/// Where `tool` is in the current layout: "Toolbar" for its button on the Tools panel, or the name +/// of the toolbar made with New Toolbar that holds it, followed by ", in the group", naming +/// the tool its slot's button shows, when the tool is hidden in that slot's group and the group is +/// not torn off into a strip; "All Tools" +/// when no toolbar holds it. A toolbar shown now comes first: the Tools panel, then the toolbars +/// made with New Toolbar; then a hidden Tools panel, then hidden toolbars made with New Toolbar. +/// Toolbars are hidden in Presentation Mode and while Tab hides the panels. +fn tool_home(app: &VectorcraftApp, tool: &str) -> String { + let lang = crate::i18n::current(); + let place = |name: &str, shown: Option<&str>| match shown.filter(|s| *s != tool).and_then(vectorcraft_tools::tool_info) { + // The tool goes in first, so a toolbar named with a placeholder keeps its name. + Some(t) => crate::i18n::fmt(tl!("{toolbar}, in the {tool} group"), &[("tool", crate::i18n::tr(lang, t.label)), ("toolbar", name)]), + None => name.to_string(), + }; + let toolbars_shown = app.ui.screen_mode < 3 && app.ui.tab_hid.is_none(); + let main = crate::toolbar::slots(app).into_iter().map(|(_, s)| s).find(|s| s.contains(&tool)); + // A group torn off into a strip shows each of its tools on its own button. + let main = main.map(|slot| { + let torn_off = slot.len() > 1 && crate::toolbar::is_floating(app, None, slot[0]); + place(tl!("Toolbar"), if torn_off { None } else { Some(crate::toolbar::shown_tool(app, &slot)) }) + }); + let active = app.session.tool_id(); + let custom = |shown: bool| { + app.ui.custom_toolbars.iter().filter(|b| b.shown == shown).find_map(|bar| { + let slot = bar.slots.iter().find(|s| s.iter().any(|t| t == tool))?; + let tools: Vec<&'static str> = slot.iter().filter_map(|id| vectorcraft_tools::tool_info(id).map(|t| t.id)).collect(); + if tools.len() > 1 && tools.first().is_some_and(|first| crate::toolbar::is_floating(app, Some(&bar.name), first)) { + return Some(place(&bar.name, None)); + } + Some(place(&bar.name, crate::custom_toolbars::shown_tool(bar, active, &tools))) + }) + }; + if toolbars_shown { + if app.ui.toolbar + && let Some(main) = &main + { + return main.clone(); + } + if let Some(bar) = custom(true) { + return bar; + } + } + main.or_else(|| custom(true)).or_else(|| custom(false)).unwrap_or_else(|| tl!("All Tools").to_string()) +} + +/// What screen readers read for a result row, and its hover text: its kind, its label, where it +/// lives (`home`) and its shortcut, after commas. +fn row_label(e: &Entry, home: &str) -> String { let shortcut = menus::shown_shortcut(&e.shortcut); - if shortcut.is_empty() { e.shown.clone() } else { format!("{}, {shortcut}", e.shown) } + let kind = kind_of(e).1; + let start = format!("{kind}, {}, {home}", label_of(e)); + if shortcut.is_empty() { start } else { format!("{start}, {shortcut}") } +} + +/// A control the highlighted result's callout can point at ([`note_spot`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SpotAt { + /// A title of the in-window menu bar, by its English name. + Menu(String), + /// A slot's button on the Tools panel (toolbar none) or on the toolbar made with New Toolbar of + /// this name, and the ids of the tools its group holds. + Slot(Option, Vec), + /// A tool's button on a strip torn off the Tools panel (toolbar none) or off the toolbar made + /// with New Toolbar of this name, and the tool's id. + Strip(Option, String), +} + +/// Where a control was drawn: the viewport and pass, its layer, the clip rectangle and its own. +#[derive(Clone, Debug)] +struct Spot { + at: SpotAt, + viewport: egui::ViewportId, + pass: u64, + layer: egui::LayerId, + clip: egui::Rect, + rect: egui::Rect, +} + +fn spots_id() -> egui::Id { + egui::Id::unique("palette-spots") +} + +/// Where the palette says whether it is open, for [`note_spot`]. +fn spots_wanted_id() -> egui::Id { + egui::Id::unique("palette-spots-wanted") +} + +/// While the palette is open, notes that `ui` drew the control `at` at `rect` in this pass, so the +/// highlighted result's callout can point at it. The menu bar and the toolbars draw before the +/// palette in each pass; `at` is built only while the palette is open. A control that is not +/// wholly in view ([`in_view`]) is not noted, so a pass notes no more controls than the window +/// shows. +pub(crate) fn note_spot(ui: &egui::Ui, rect: egui::Rect, at: impl FnOnce() -> SpotAt) { + let ctx = ui.ctx(); + if !ctx.data(|d| d.get_temp::(spots_wanted_id())).unwrap_or(false) || !in_view(ctx.content_rect(), ui.clip_rect(), rect) { + return; + } + let viewport = ctx.viewport_id(); + let pass = ctx.cumulative_pass_nr_for(viewport); + let spot = Spot { at: at(), viewport, pass, layer: ui.layer_id(), clip: ui.clip_rect(), rect }; + ctx.data_mut(|d| add_spot(d.get_temp_mut_or_default::>(spots_id()), spot)); +} + +/// Adds `spot` to `list`. The first control a viewport notes in a pass drops every control it +/// noted in earlier passes, so the list holds at most one pass of each viewport: no more controls +/// than its windows drew wholly in view. +fn add_spot(list: &mut Vec, spot: Spot) { + if list.iter().rev().find(|s| s.viewport == spot.viewport).is_some_and(|s| s.pass != spot.pass) { + list.retain(|s| s.viewport != spot.viewport || s.pass == spot.pass); + } + list.push(spot); +} + +/// Is `rect`, drawn clipped to `clip`, wholly in view: inside `clip` and inside the window `screen`? +fn in_view(screen: egui::Rect, clip: egui::Rect, rect: egui::Rect) -> bool { + rect.is_finite() && clip.expand(0.5).contains_rect(rect) && screen.expand(0.5).contains_rect(rect) +} + +/// The control noted as `at` in this pass of this viewport, when it is wholly in view and no +/// window or toolbar lies over it ([`covered`]). +fn spot(ctx: &egui::Context, at: impl Fn(&SpotAt) -> bool) -> Option { + let viewport = ctx.viewport_id(); + let pass = ctx.cumulative_pass_nr_for(viewport); + let screen = ctx.content_rect(); + let found = ctx.data_mut(|d| { + d.get_temp_mut_or_default::>(spots_id()) + .iter() + .find(|s| s.viewport == viewport && s.pass == pass && at(&s.at) && in_view(screen, s.clip, s.rect)) + .cloned() + })?; + (!covered(ctx, &found)).then_some(found) +} + +/// Does a shown area above the control `s`'s layer overlap it: a floating panel, a toolbar or a +/// menu? The palette's own backdrop, popup and Recent Commands list do not count (the callout keeps +/// off the popup itself, [`aim`]), nor do tooltips. A layer that is not an area (a docked panel's) +/// is under every area of a higher order. +fn covered(ctx: &egui::Context, s: &Spot) -> bool { + let own = [egui::Id::unique("palette-backdrop"), egui::Id::unique("palette"), recent_list_id()]; + ctx.memory(|m| { + let order: Vec = m.layer_ids().collect(); + let at = order.iter().position(|l| *l == s.layer); + order.iter().enumerate().any(|(i, l)| { + let above = match at { + Some(at) => i > at, + None => l.order > s.layer.order, + }; + above + && l.order < egui::Order::Tooltip + && !own.contains(&l.id) + && m.areas().is_visible(l) + && m.area_rect(l.id).is_some_and(|r| r.intersects(s.rect)) + }) + }) +} + +/// Where the highlighted result lives, as the palette points at it. +enum Pointer { + /// The control that shows the home, the callout's text, and the footer line that names the + /// home when the popup covers the control. + At(Spot, String, String), + /// No control in view shows the home: the footer shows the text. + Footer(String), +} + +/// The footer line for a home that no control in view shows. +fn unseen_line(home: &str) -> String { + crate::i18n::fmt(tl!("{home}, not shown now"), &[("home", home)]) +} + +fn unseen(home: &str) -> Pointer { + Pointer::Footer(unseen_line(home)) +} + +/// How the callout at a control keeps off the palette's popup and off the control. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Aim { + /// Outline the control and show the text in a box beside it. + Box, + /// Outline the control and show the text in the footer: a box beside the control would cover + /// the popup or the control. + Outline, + /// The popup covers the control: no callout, and the footer names the home. + Covered, +} + +/// How the callout at `place` with `text` keeps off the popup at `popup` and off the control. +fn aim(ctx: &egui::Context, popup: Option, place: &Spot, text: &str) -> Aim { + if popup.is_some_and(|p| p.intersects(place.rect)) { + return Aim::Covered; + } + let boxed = callout_box(ctx, place, text, popup).0; + if popup.is_some_and(|p| p.intersects(boxed)) || boxed.intersects(place.rect) { Aim::Outline } else { Aim::Box } +} + +/// The callout for the highlighted result `e`. A tool points at its slot's button on a shown +/// toolbar, in the order of [`tool_home`], or at its button on a strip torn off its group; a +/// result with an item of the in-window menu bar points at the menu's title. A native menu bar, +/// a home that is not in view now and a result with no menu item get a footer line instead. +fn pointer(app: &VectorcraftApp, ctx: &egui::Context, e: &Entry) -> Pointer { + let lang = crate::i18n::current(); + if let Some(id) = e.id.strip_prefix("tool:") { + let Some(tool) = vectorcraft_tools::tool_info(id) else { return unseen(&tool_home(app, id)) }; + let Ok(found) = crate::panels::learn::locate::find(app, tool.id, true) else { return unseen(&tool_home(app, id)) }; + let bar = match &found.target { + crate::panels::learn::locate::Target::Tools => None, + crate::panels::learn::locate::Target::Custom(name) => Some(name.as_str()), + crate::panels::learn::locate::Target::AllTools => return unseen(&tool_home(app, id)), + }; + let place = if found.location == "strip" { + spot(ctx, |at| matches!(at, SpotAt::Strip(b, t) if b.as_deref() == bar && t == tool.id)) + } else { + spot(ctx, |at| matches!(at, SpotAt::Slot(b, tools) if b.as_deref() == bar && tools.iter().any(|t| t == tool.id))) + }; + let Some(place) = place else { return unseen(&tool_home(app, id)) }; + let text = match found.shown.filter(|_| found.location == "flyout").and_then(vectorcraft_tools::tool_info) { + Some(group) => crate::i18n::fmt(tl!("In the {group} group: press and hold to open it"), &[("group", crate::i18n::tr(lang, group.label))]), + None => crate::i18n::tr(lang, tool.label).to_string(), + }; + return Pointer::At(place, text, tool_home(app, id)); + } + let Some(path) = &e.home else { + let shortcut = menus::shown_shortcut(&e.shortcut); + let none = tl!("No menu item"); + return Pointer::Footer(if shortcut.is_empty() { none.to_string() } else { format!("{none}, {shortcut}") }); + }; + // The native bar's application menu gives its items no label of their own. + let full = match e.menu_item { + "" => shown_label(lang, path), + _ => format!("{} › {}", shown_label(lang, path), item_label(lang, e)), + }; + let in_bar = crate::i18n::fmt(tl!("In the menu bar: {path}"), &[("path", &full)]); + if app.services.native_menu.is_some() { + return Pointer::Footer(in_bar); + } + let title = path.split(" › ").next().unwrap_or_default(); + match spot(ctx, |at| matches!(at, SpotAt::Menu(t) if t == title)) { + Some(place) => Pointer::At(place, full, in_bar), + None => unseen(&full), + } +} + +/// The callout drawn in the last pass: the outlined control, the box (none when the footer shows +/// the text) and the text. Only tests keep it. +type Callout = Option<(egui::Rect, Option, String)>; + +#[cfg(test)] +fn callout_id() -> egui::Id { + egui::Id::unique("palette-callout") +} + +/// The callout's layer, above the palette's backdrop and popup. +fn callout_painter(ctx: &egui::Context) -> egui::Painter { + ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("palette-callout-layer"))).with_clip_rect(ctx.content_rect()) +} + +/// Where the box with `text` goes beside the control `place`, and its text laid out: under a menu +/// title, and on the canvas side of a toolbar's button (its right when the button is in the +/// window's left half). Beside a button, the text wraps to at most [`BOX_ROWS`] rows to fit +/// between the button and the window's edge, or the palette's popup at `popup` when the popup is +/// on that side. The box stays inside the window. +fn callout_box(ctx: &egui::Context, place: &Spot, text: &str, popup: Option) -> (egui::Rect, Arc) { + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let r = place.rect; + let menu = matches!(place.at, SpotAt::Menu(_)); + let right = r.center().x <= screen.center().x; + let mut width = screen.width() - 2.0 * BOX_PAD.x - 8.0; + if !menu { + // Beside a button, the text wraps to fit between the button and the window's edge. + // Narrower room than this leaves the box over the button, and the footer shows the text + // instead ([`aim`]). + let room = if right { screen.right() - r.right() } else { r.left() - screen.left() } - 10.0 - 2.0 * BOX_PAD.x; + if room >= 80.0 { + width = width.min(room); + } + } + if let Some(p) = popup.filter(|_| !menu) { + let room = if right { p.left() - r.right() } else { r.left() - p.right() } - 10.0 - 2.0 * BOX_PAD.x; + // Narrower room than this leaves the box where it would cover the popup, and the footer + // shows the text instead ([`aim`]). + if room >= 80.0 { + width = width.min(room); + } + } + let mut job = egui::text::LayoutJob::simple(text.to_owned(), egui::FontId::proportional(12.0), t.text, width.max(0.0)); + job.wrap = egui::text::TextWrapping { + max_width: width.max(0.0), + max_rows: if menu { 1 } else { BOX_ROWS }, + break_anywhere: false, + overflow_character: Some('…'), + }; + let galley = callout_painter(ctx).layout_job(job); + let size = galley.size() + 2.0 * BOX_PAD; + let at = if menu { + egui::pos2(r.left(), r.bottom() + 4.0) + } else if right { + egui::pos2(r.right() + 6.0, r.center().y - size.y / 2.0) + } else { + egui::pos2(r.left() - 6.0 - size.x, r.center().y - size.y / 2.0) + }; + let x = at.x.min(screen.right() - 4.0 - size.x).max(screen.left() + 4.0); + let y = at.y.min(screen.bottom() - 4.0 - size.y).max(screen.top() + 4.0); + (egui::Rect::from_min_size(egui::pos2(x, y), size), galley) +} + +/// How many rows the text of a box beside a toolbar's button wraps to at most. +const BOX_ROWS: usize = 3; + +/// The space between the callout box's border and its text. +const BOX_PAD: egui::Vec2 = egui::vec2(6.0, 3.0); + +/// Outline the control `place`, and with `text` show it in a box beside it ([`callout_box`], with +/// the popup at `popup`). Returns the box. +fn callout(ctx: &egui::Context, place: &Spot, text: Option<&str>, popup: Option) -> Option { + let t = Tokens::get(ctx); + let painter = callout_painter(ctx); + crate::panels::learn::locate::outline(&painter.with_clip_rect(place.clip.intersect(ctx.content_rect())), place.rect, t.selection); + let (rect, galley) = callout_box(ctx, place, text?, popup); + painter.rect(rect, 4.0, t.panel, egui::Stroke::new(1.0, t.selection), egui::StrokeKind::Inside); + painter.galley(rect.min + BOX_PAD, galley, t.text); + Some(rect) } /// The line under the results: how many results matched, how many of them the list holds when it @@ -502,6 +912,41 @@ fn name_galley(painter: &egui::Painter, name: &str, font: egui::FontId, color: e painter.layout_job(job) } +/// A result row's label and home laid out in `width` points, and whether either was cut short. The +/// home goes after the label in the smaller dim text and is cut first; when the label alone does +/// not fit, the home is left out and the label is cut before the id it shows after its name +/// ([`distinct_names`]), which stays whole unless the id alone is wider than the row. +fn row_galleys( + painter: &egui::Painter, + e: &Entry, + home: &str, + font: egui::FontId, + color: egui::Color32, + dim: egui::Color32, + width: f32, +) -> (Arc, Option>, bool) { + let label = label_of(e); + let full = name_galley(painter, label, font.clone(), color, f32::INFINITY); + let room = width - full.size().x - 10.0; + if full.size().x <= width { + if room < HOME_TEXT { + return (full, None, !home.is_empty()); + } + let home = name_galley(painter, home, egui::FontId::new(HOME_TEXT, font.family), dim, room); + let cut = home.elided; + return (full, Some(home), cut); + } + let suffix = format!(" ({})", e.id); + let (head, suffix) = match label.strip_suffix(suffix.as_str()) { + Some(head) => (head, suffix), + None => (label, String::new()), + }; + let suffix_width = name_galley(painter, &suffix, font.clone(), color, f32::INFINITY).size().x; + let cut_head = name_galley(painter, head, font.clone(), color, width - suffix_width); + let shown: String = cut_head.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.chr)).collect(); + (name_galley(painter, &format!("{shown}{suffix}"), font, color, width), None, true) +} + /// The scroll offset that keeps row `sel` in a list `view` points tall that was scrolled to `offset`. fn offset_showing(sel: usize, offset: f32, view: f32) -> f32 { let top = sel as f32 * ROW_HEIGHT; @@ -569,6 +1014,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // another widget, such as a field in a window above the backdrop. let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); + // The menu bar and the toolbars note where they draw their controls only while the palette is + // open; the pass that opens it asks for another, which they draw noting them. + let wanted = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::(spots_wanted_id()), app.ui.palette_open)); + if app.ui.palette_open && !wanted { + ctx.request_repaint(); + } else if !app.ui.palette_open && wanted { + ctx.data_mut(|d| { + d.remove::>(spots_id()); + #[cfg(test)] + d.remove::(callout_id()); + }); + } if !app.ui.palette_open { let field = ctx.data_mut(|d| { let field = d.get_temp::(field_id); @@ -672,6 +1129,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let screen = ctx.content_rect(); // The highlighted result the rows and the field's description are drawn with. let mut drawn = sel; + // The control that shows where the highlighted result lives, the callout's text, and how the + // footer drawn in this pass keeps the callout off the popup. + let mut pointed: Option<(Spot, String, Aim)> = None; + // The popup as the last pass laid it out: the footer is drawn before this pass's popup has its + // size, and the callout is checked again against that size after the popup is drawn. + let last_popup = ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))); // The backdrop covers the canvas, the toolbars, the docked panels and the app bar under the // popup, in the order of a modal dialog's backdrop (`dialogs::modal::backdrop`), so the press // that closes the palette does not press a control under it. Windows in the Foreground order @@ -681,7 +1144,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); // The area keeps itself inside the window (egui's `Area::constrain` is on), so in a window too // short for the field, one row and the footer below TOP, the popup moves up. - egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, TOP]).show(ctx, |ui| { + let popup_area = egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, TOP]); + let area = popup_area.show(ctx, |ui| { let margin: i8 = 10; egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(margin)).show(ui, |ui| { ui.set_width(520.0); @@ -736,11 +1200,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let resized = (view - last_view).abs() > 0.5; // Screen readers stay on the field: its description names the highlighted result and // its place among every match, as the footer counts them. + let mut described = None; if let Some(e) = matches.get(sel) { let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; let pos = (rank + 1).to_string(); let of = total.to_string(); - let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + let name = row_label(e, &home_text(app, e)); + let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); + described = Some(said.clone()); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } if n > 0 { @@ -765,16 +1232,29 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); + let home = home_text(app, e); + let said = row_label(e, &home); let p = ui.painter(); let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; - let name_at = rect.left() + 8.0; - let name = name_galley(p, &e.shown, font, t.text, name_end - name_at); - p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, t.text); + let icon = egui::Rect::from_center_size( + egui::pos2(rect.left() + 8.0 + KIND_ICON / 2.0, rect.center().y), + egui::Vec2::splat(KIND_ICON), + ); + crate::icons::paint(ui, kind_of(e).0, icon, t.icon); + let name_at = icon.right() + 6.0; + let (label, home, cut) = row_galleys(p, e, &home, font, t.text, t.text_dim, name_end - name_at); + let home_at = name_at + label.size().x + 10.0; + p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, t.text); + if let Some(home) = home { + p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, t.text_dim); + } + // A row whose text is cut short shows all of it while the pointer rests on it. + let resp = if cut { resp.on_hover_text(said.clone()) } else { resp }; // `WidgetInfo::selected` reaches screen readers as a toggled state, so the // row sets the selected state on its node itself. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, row_label(e))); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, said.clone())); ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); if resp.clicked() { run = Some(e.id.clone()); @@ -791,7 +1271,45 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); } ui.add_space(6.0); - ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); + // The highlighted result's home, after a pointer or a scroll moved the highlight too. In + // the pass that opens the palette, the menu bar and the toolbars have noted nothing yet, + // and the next pass shows it. + let mut hint = None; + match matches.get(sel).filter(|_| wanted).map(|e| pointer(app, ui.ctx(), e)) { + Some(Pointer::At(place, text, covered)) => { + let how = aim(ui.ctx(), last_popup, &place, &text); + hint = match how { + Aim::Box => None, + Aim::Outline => Some(text.clone()), + Aim::Covered => Some(covered), + }; + // Screen readers get the text of a box beside a tool's button, such as how to + // open the group that hides the tool, with the field's description, unless the + // description already holds it. + if how == Aim::Box + && !matches!(place.at, SpotAt::Menu(_)) + && sel == drawn + && let Some(said) = &described + && !said.contains(text.as_str()) + { + let said = format!("{said}, {text}"); + ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); + } + pointed = Some((place, text, how)); + } + Some(Pointer::Footer(text)) => hint = Some(text), + None => {} + } + ui.scope(|ui| { + // The footer stays one line of text tall, as the list's height counts it. + ui.spacing_mut().interact_size.y = 0.0; + ui.horizontal(|ui| { + ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); + if let Some(hint) = hint { + ui.add(egui::Label::new(egui::RichText::new(hint).color(t.text_dim)).truncate()); + } + }); + }); if !list_open && !history_focused && ui.input(|i| i.key_pressed(egui::Key::Enter)) @@ -816,6 +1334,24 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let popup = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("palette")); let list = egui::LayerId::new(egui::Order::Foreground, recent_list_id()); let outside = presses.into_iter().any(|p| !ctx.layer_id_at(p).is_some_and(|l| l == popup || l == list)); + // The callout keeps off the popup as drawn in this pass. When the popup's new size changes + // which of the three cases applies, the next pass draws the footer to match. + let now = Some(area.response.rect); + let shown: Callout = pointed.and_then(|(place, text, before)| { + let how = aim(ctx, now, &place, &text); + if how != before { + ctx.request_repaint(); + } + match how { + Aim::Covered => None, + Aim::Outline => Some((place.rect, callout(ctx, &place, None, now), text)), + Aim::Box => Some((place.rect, callout(ctx, &place, Some(&text), now), text)), + } + }); + #[cfg(test)] + ctx.data_mut(|d| d.insert_temp::(callout_id(), shown)); + #[cfg(not(test))] + drop(shown); // The pointer or a scroll moved the highlight after the rows were drawn: the next frame draws // it where it now is. if sel != drawn { @@ -1934,6 +2470,12 @@ mod tests { self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() } + /// What screen readers read for result `id`'s row. + fn said(&self, id: &str) -> String { + let entries = entries(&self.ctx, Lang::EN); + entries.iter().find(|e| e.id == id).map(|e| row_label(e, &home_text(&self.app, e))).unwrap() + } + /// The results the palette lists for its query. fn listed(&self) -> Vec { let entries = entries(&self.ctx, Lang::EN); @@ -2042,8 +2584,7 @@ mod tests { let nodes = open.press(egui::Key::ArrowDown, 15); assert_eq!(open.highlighted(), 15); let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); - let entries = entries(&open.ctx, Lang::EN); - let want = entries.iter().find(|e| e.id == listed[15]).map(row_label).unwrap(); + let want = open.said(&listed[15]); assert_eq!(lit.len(), 1, "{lit:?}"); assert_eq!(lit[0].0, want); let popup = open.popup(); @@ -2118,7 +2659,7 @@ mod tests { let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); assert_eq!(lit.len(), 1, "{lit:?}"); assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); - assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); + assert_eq!(lit[0].0, open.said(&open.listed()[sel])); } /// Page Down, Up and Enter pressed in one frame move the highlight in that order, and Enter @@ -2211,7 +2752,7 @@ mod tests { assert!(open.repaint, "the frame that moved the highlight asks for another"); let nodes = open.frame(vec![]); let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); - let label = entries.iter().find(|e| e.id == listed[3]).map(row_label).unwrap(); + let label = open.said(&listed[3]); assert_eq!(lit, std::slice::from_ref(&label)); assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select").len())); } @@ -2233,6 +2774,206 @@ mod tests { out.textures_delta.clear(); } + /// The label and home of English result `id`'s row with the app's current layout. + fn label_and_home(app: &VectorcraftApp, id: &str) -> (String, String) { + crate::i18n::set_current(Lang::EN); + let entries = build(Lang::EN); + let e = entries.iter().find(|e| e.id == id).unwrap_or_else(|| panic!("{id} is listed")); + (label_of(e).to_string(), home_text(app, e)) + } + + /// A row shows its label without the menu path, and the menu path of the item of the menu bar + /// that runs it after it: with that item's label when it differs, and "No menu item" for a + /// command no item runs. + #[test] + fn rows_show_where_each_result_lives() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let row = |id: &str| label_and_home(&app, id); + assert_eq!(row("effect:stylize.roundCorners"), ("Round Corners…".into(), "Effect › Stylize".into())); + assert_eq!(row("panel:layers"), ("Layers".into(), "Window".into())); + assert_eq!(row("object.group"), ("Group".into(), "Object".into())); + assert_eq!(row("app.quit").1, "File › Exit"); + // Window › Learn runs the Learn command as well as showing the Learn panel. + assert_eq!(row("window.learn").1, "Window"); + let entries = build(Lang::EN); + let learn = entries.iter().find(|e| e.id == "window.learn").expect("the Learn command"); + assert_eq!(learn.kind, search::kind("object.group", Some("Object")), "the Learn command ranks as a command of the menu bar"); + let none = entries.iter().find(|e| e.home.is_none() && !e.id.starts_with("tool:")).expect("a command with no menu item"); + assert_eq!((label_of(none), home_text(&app, none).as_str()), (none.shown.as_str(), "No menu item")); + // A path that keeps two names apart stays, unless the home shows it: the Knife tool's row + // drops the Tools in front of its name, and an Other Library… row shows its library menu + // as its home only. + assert_eq!(row("tool:knife").0, "Knife"); + let other: Vec<(&str, String)> = + entries.iter().filter(|e| e.shown.ends_with("Other Library…")).map(|e| (label_of(e), home_text(&app, e))).collect(); + assert!(other.len() >= 2 && other.iter().all(|(label, home)| *label == "Other Library…" && home.starts_with("Window › ")), "{other:?}"); + let kept = entries.iter().find(|e| e.label_at == 0 && e.shown.contains(" › ")).expect("a row that keeps its path"); + assert!(kept.home.as_deref().is_none_or(|h| !kept.shown.starts_with(&format!("{h} › "))), "{}", kept.shown); + for e in entries.iter().filter(|e| e.label_at > 0) { + assert!(e.home.is_some() || e.id.starts_with("tool:"), "{} has no home but drops its path", e.id); + } + } + + /// No two results' rows show the same kind, label and home, in any language, with the menu bar + /// in the window or the native one. + #[test] + fn no_two_rows_read_alike() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut alike = vec![]; + for lang in Lang::all() { + crate::i18n::set_current(lang); + for native in [false, true] { + let mut seen = std::collections::HashMap::new(); + for e in &build_in(lang, native) { + let row = (kind_of(e).1, label_of(e).to_string(), home_text(&app, e)); + if let Some(other) = seen.insert(row.clone(), e.id.clone()) + && other != e.id + { + alike.push(format!("{} (native {native}): {other} and {}: {row:?}", lang.code(), e.id)); + } + } + } + } + crate::i18n::set_current(Lang::EN); + assert!(alike.is_empty(), "{}", alike.join("\n")); + } + + /// Every catalog translates the words a row's kind and home are read with. + #[test] + fn catalogs_translate_the_kind_and_home_words() { + let words = ["Tool", "Panel", "Effect", "Filter", "Command", "Toolbar", "{toolbar}, in the {tool} group", "All Tools", "No menu item"]; + let missing: Vec = Lang::all() + .filter(|l| *l != Lang::EN) + .flat_map(|l| words.iter().filter(move |w| !crate::i18n::has(l, w)).map(move |w| format!("{}: {w}", l.code()))) + .collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + + /// A tool's row names the toolbar it is on, and the tool its slot's button shows while it is + /// hidden in that slot's group. A toolbar shown now comes before a hidden Tools panel, which + /// comes before a hidden toolbar made with New Toolbar. + #[test] + fn a_tool_row_names_its_toolbar_slot() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let home = |app: &VectorcraftApp, id: &str| label_and_home(app, id).1; + assert_eq!(home(&app, "tool:groupSelection"), "Toolbar, in the Direct Selection Tool group"); + assert_eq!(home(&app, "tool:directSelection"), "Toolbar"); + app.select_tool("groupSelection"); + assert_eq!(home(&app, "tool:groupSelection"), "Toolbar"); + assert_eq!(home(&app, "tool:directSelection"), "Toolbar, in the Group Selection Tool group"); + let bar = |name: &str, slot: &[&str], shown: bool| crate::state::CustomToolbar { + name: name.into(), + slots: vec![slot.iter().map(|t| t.to_string()).collect()], + shown, + pos: [0.0, 0.0], + dock: None, + dock_right: false, + slot_tool: Default::default(), + double: false, + floating: vec![], + }; + // Window › Tools hides the Tools panel while a toolbar made with New Toolbar holds the Pen + // Tool: the row names that toolbar. + app.ui.toolbar = false; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.custom_toolbars.push(bar("Drawing", &["pen", "curvature"], true)); + assert_eq!(home(&app, "tool:pen"), "Drawing"); + assert_eq!(home(&app, "tool:curvature"), "Drawing, in the Pen Tool group"); + app.ui.custom_toolbars[0].name = "{tool}".into(); + assert_eq!(home(&app, "tool:curvature"), "{tool}, in the Pen Tool group"); + app.ui.custom_toolbars[0].name = "Drawing".into(); + // Tab hides the toolbars made with New Toolbar too: the hidden Tools panel comes first. + app.ui.tab_hid = Some(crate::state::TabHid { dock: true, toolbar: true, control_bar: true }); + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.tab_hid = None; + // The Tools panel shown again comes first. + app.ui.toolbar = true; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + // In Presentation Mode no toolbar shows; the tool still lives on the Tools panel. + app.ui.screen_mode = 3; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.screen_mode = 0; + // A tool that only a hidden toolbar made with New Toolbar holds is named on it, and one no + // toolbar holds is in All Tools. + let on_tools: Vec<&str> = crate::toolbar::slots(&app).into_iter().flat_map(|(_, s)| s).collect(); + let loose = vectorcraft_tools::catalog::all_tools().map(|t| t.id).find(|t| !on_tools.contains(t)).expect("a tool not on the Tools panel"); + let id = format!("tool:{loose}"); + assert_eq!(home(&app, &id), "All Tools"); + app.ui.custom_toolbars.push(bar("Cutting", &[loose], false)); + assert_eq!(home(&app, &id), "Cutting"); + } + + /// A row too narrow for its label and home cuts the home first; a label that does not fit + /// alone is cut before the id it shows after its name, which stays whole. + #[test] + fn a_narrow_row_cuts_the_home_first_and_keeps_the_id() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let entries = build(Lang::EN); + let keyed = entries.iter().find(|e| e.shown.ends_with(&format!(" ({})", e.id))).expect("a result that shows its id"); + let copy = entries.iter().find(|e| e.id == "edit.copy").expect("Copy"); + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let p = ui.painter(); + let lay = |e: &Entry, home: &str, width: f32| row_galleys(p, e, home, font.clone(), egui::Color32::WHITE, egui::Color32::GRAY, width); + let text = |g: &egui::Galley| g.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.chr)).collect::(); + let (label, home, cut) = lay(copy, "Edit", 400.0); + assert_eq!((text(&label), home.map(|h| text(&h)), cut), ("Copy".into(), Some("Edit".into()), false)); + let long = "A Menu › A Submenu With A Long Name › Another Submenu"; + let (label, home, cut) = lay(copy, long, 160.0); + let home = home.expect("some of the home fits"); + assert!(cut && home.elided && text(&label) == "Copy", "{}", text(&home)); + assert!(label.size().x + 10.0 + home.size().x <= 160.0 + 0.5); + // A long German menu path is cut before the label. + crate::i18n::set_current(Lang::from_code("de").expect("German")); + let german = build_in(crate::i18n::current(), false); + let deep = german + .iter() + .filter(|e| e.label_at > 0) + .max_by_key(|e| e.home.as_ref().map_or(0, |h| shown_label(crate::i18n::current(), h).chars().count())); + let deep = deep.expect("a German row with a home"); + let path = home_text(&app, deep); + crate::i18n::set_current(Lang::EN); + let label_width = name_galley(p, label_of(deep), font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + let (label, home, cut) = lay(deep, &path, label_width + 60.0); + assert!(cut && text(&label) == label_of(deep) && home.is_some_and(|h| h.elided), "{path}"); + let suffix = format!(" ({})", keyed.id); + let suffix_width = name_galley(p, &suffix, font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + let full = name_galley(p, label_of(keyed), font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + assert!(full - 5.0 > suffix_width + 20.0, "{}", label_of(keyed)); + for width in [full - 5.0, suffix_width + 20.0, suffix_width / 2.0] { + let (label, home, cut) = lay(keyed, long, width); + let shown = text(&label); + assert!(cut && home.is_none(), "{width}"); + assert!(label.size().x <= width + 0.5, "{width}: {shown} is {} wide", label.size().x); + // An id wider than the row is cut too. + assert_eq!(shown.ends_with(&format!("…{suffix}")), width > suffix_width, "{width}: {shown}"); + } + }); + out.textures_delta.clear(); + } + + /// Screen readers read a row as its kind, label, home and shortcut, and the field's + /// description names them too; the row's height is unchanged. + #[test] + fn screen_readers_hear_the_kind_and_home() { + let mut open = Open::new("round corners", WINDOW); + let nodes = open.frame(vec![]); + let said = open.said("effect:stylize.roundCorners"); + assert_eq!(said, "Effect, Round Corners…, Effect › Stylize"); + let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn"); + assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}"); + assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes)); + let open = Open::new("group selection", WINDOW); + assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group"); + let mut open = Open::new("layers", WINDOW); + let said = open.said("panel:layers"); + assert!(said.starts_with("Panel, Layers, Window"), "{said}"); + let nodes = open.frame(vec![]); + assert!(rows(&nodes).iter().any(|r| r.0 == said)); + } + /// The popup stays inside a short window, showing fewer rows when 12 don't fit; a page is the /// rows shown. #[test] @@ -2283,7 +3024,8 @@ mod tests { let mut open = Open::new("show panel", WINDOW); let listed = open.listed(); let entries = entries(&open.ctx, Lang::EN); - let label = |i: usize| entries.iter().find(|e| e.id == listed[i]).map(row_label).unwrap(); + let said: Vec = listed.iter().map(|id| open.said(id)).collect(); + let label = |i: usize| said[i].clone(); let nodes = open.frame(vec![]); // More results match than the list holds: the place counts every match, as the footer does. let total = matching(&entries, "show panel").len(); @@ -2295,10 +3037,10 @@ mod tests { let nodes = open.press(egui::Key::ArrowDown, 1); assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); // Fewer results match than the list holds. - let mut open = Open::new("copy", WINDOW); + let mut open = Open::new("eyedropper", WINDOW); let n = open.listed().len(); assert!((1..MAX_RESULTS).contains(&n), "{n}"); - let first = entries.iter().find(|e| e.id == open.listed()[0]).map(row_label).unwrap(); + let first = open.said(&open.listed()[0]); let nodes = open.frame(vec![]); assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); @@ -2780,7 +3522,7 @@ mod tests { let listed: Vec<_> = matching(&entries, "show panel").into_iter().take(MAX_RESULTS).collect(); let hidden = |e: &&&Entry| e.id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&window.app.ui, p)); let e = listed.iter().find(hidden).expect("a hidden panel's result"); - let label = row_label(e); + let label = row_label(e, &home_text(&window.app, e)); let row = rows(&nodes).into_iter().find(|r| r.0 == label).expect("its row is drawn"); let panel = e.id.strip_prefix("panel:").unwrap_or_default().to_string(); window.click(egui::pos2(window.popup().center().x, ((row.2 + row.3) / 2.0) as f32)); @@ -2868,8 +3610,567 @@ mod tests { assert!(plugin.is_some_and(|p| p < MAX_RESULTS), "the plug-in is shown: {plugin:?}"); assert_eq!(ranked.iter().position(|e| e.id == id), Some(MAX_RESULTS), "the plug-in pushed the highlight past the limit"); assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); - let label = row_label(ranked[MAX_RESULTS]); + let label = row_label(ranked[MAX_RESULTS], &home_text(&open.app, ranked[MAX_RESULTS])); assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); } + + impl Window { + /// Opens the palette on `query` and draws until the toolbars and the menu bar have noted + /// their controls: the last frame's screen-reader tree. + fn search(&mut self, query: &str) -> Vec { + self.app.ui.palette_open = true; + self.app.ui.palette_query = query.into(); + self.frame(vec![]); + self.frame(vec![]) + } + + /// The highlighted result's id. + fn highlighted(&self) -> String { + self.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().4 + } + + /// The callout the last frame drew: the outlined control, the box and its text. + fn callout(&self) -> Callout { + self.ctx.data(|d| d.get_temp::(callout_id())).flatten() + } + + /// The text of the labels in the popup in the screen-reader tree `nodes`: the footer's. + fn popup_labels(&self, nodes: &[egui::accesskit::Node]) -> Vec { + let popup = self.popup(); + nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::Label) + .filter(|n| n.bounds().is_some_and(|b| popup.contains(egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)))) + .filter_map(|n| n.label().or(n.value()).map(str::to_string)) + .collect() + } + } + + /// The bounds of the control whose screen-reader name is `name`, alone or followed by its + /// shortcut in parentheses. + fn bounds_of(nodes: &[egui::accesskit::Node], name: &str) -> egui::Rect { + let at = button_at(nodes, name); + let node = nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::Button) + .find(|n| n.bounds().is_some_and(|b| ((b.x0 + b.x1) / 2.0) as f32 == at.x && ((b.y0 + b.y1) / 2.0) as f32 == at.y)) + .unwrap(); + let b = node.bounds().unwrap(); + egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)) + } + + /// Highlighting a result with an item of the in-window menu bar outlines that menu's title, as + /// drawn in the same frame, and the box under it shows the item's whole path. + #[test] + fn the_highlighted_result_outlines_its_menu_title() { + let mut window = Window::new(); + let nodes = window.search("round corners"); + assert_eq!(window.highlighted(), "effect:stylize.roundCorners"); + let (outlined, callout, text) = window.callout().expect("a callout"); + assert_eq!(text, "Effect › Stylize › Round Corners…"); + assert_eq!(outlined, bounds_of(&nodes, "Effect")); + let callout = callout.expect("a box"); + assert!(callout.top() >= outlined.bottom(), "the box is under the title: {callout:?} {outlined:?}"); + // A panel's home is the Window menu. + window.search("layers"); + assert_eq!(window.highlighted(), "panel:layers"); + let (outlined, _, text) = window.callout().expect("a callout"); + assert_eq!(text, "Window › Layers"); + assert_eq!(outlined, bounds_of(&window.frame(vec![]), "Window")); + // Closing the palette ends the callout. + window.app.ui.palette_open = false; + window.frame(vec![]); + assert_eq!(window.callout(), None); + } + + struct NativeMenus; + impl crate::native_menu::Backend for NativeMenus { + fn sync(&mut self, _: &crate::native_menu::MenuBar) {} + fn drain(&mut self) -> Vec { + Vec::new() + } + } + + /// With the system's menu bar, nothing is drawn over it: the footer names the menu path. + #[test] + fn with_a_native_menu_bar_the_footer_names_the_path() { + let mut window = Window::new(); + window.app.services.native_menu = Some(crate::native_menu::NativeMenu::new(Box::new(NativeMenus))); + let nodes = window.search("round corners"); + assert_eq!(window.highlighted(), "effect:stylize.roundCorners"); + assert_eq!(window.callout(), None); + assert!(labels(&nodes).contains(&"In the menu bar: Effect › Stylize › Round Corners…".to_string()), "{:?}", labels(&nodes)); + // The application menu's items have no label of their own: the path ends at the menu. + let nodes = window.search("help.about"); + assert_eq!(window.highlighted(), "help.about"); + let menu = format!("In the menu bar: {}", crate::native_menu::APP_NAME); + assert!(labels(&nodes).contains(&menu), "{:?}", labels(&nodes)); + } + + /// A built-in effect's item in the path translates by its effect id, as the Effect menu shows + /// it, another item by its command id, and a plug-in's name stays as written. + #[test] + fn the_path_names_an_effect_item_as_the_effect_menu_does() { + let mut window = Window::new(); + window.app.services.native_menu = Some(crate::native_menu::NativeMenu::new(Box::new(NativeMenus))); + let fr = Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let list = entries(&window.ctx, fr); + let add = list.iter().find(|e| e.id == "effect:pathfinder.add").expect("the Add effect"); + let shown = match pointer(&window.app, &window.ctx, add) { + Pointer::Footer(text) => text, + Pointer::At(_, text, _) => text, + }; + crate::i18n::set_current(Lang::EN); + assert!(shown.ends_with(" › Réunion"), "{shown}"); + // A live-effect plug-in's name stays as written, as the Effect menu shows it. + let plugin = Entry { + id: format!("effect:{}", vectorcraft_plugins::effect::effect_id("test.ui.add")), + shortcut: String::new(), + shown: "Add".into(), + haystack: String::new(), + home: Some("Effect › Plug-ins".into()), + menu_item: "Add", + kind: 0, + label_at: 0, + names_item: false, + }; + assert_ne!(crate::i18n::tr(fr, "Add"), "Add"); + assert_eq!(item_label(fr, &plugin), "Add"); + // So does a filter plug-in's name, as Object › Plug-ins shows it. + let filter = Entry { id: "plugin:test.ui.add".into(), home: Some("Object › Plug-ins".into()), ..plugin }; + assert_eq!(item_label(fr, &filter), "Add"); + // Another item translates by the id of the command it runs, as the menu bar draws it. + let es = Lang::from_code("es").unwrap(); + let close = entries(&window.ctx, es).iter().find(|e| e.id == "file.close").map(|e| (e.menu_item, item_label(es, e))); + assert_ne!(crate::i18n::tr(es, "Close"), "Cerrar archivo"); + assert_eq!(close, Some(("Close", "Cerrar archivo"))); + } + + /// A tool hidden in a group outlines its group's button and says how to open the group; once + /// chosen from the group, the button shows it and the box names the tool alone. The box is on + /// the canvas side of the toolbar. + #[test] + fn a_tool_result_outlines_its_toolbar_slot() { + let mut window = Window::new(); + let nodes = window.search("group selection tool"); + assert_eq!(window.highlighted(), "tool:groupSelection"); + let (outlined, callout, text) = window.callout().expect("a callout"); + assert_eq!(text, "In the Direct Selection Tool group: press and hold to open it"); + assert_eq!(outlined, bounds_of(&nodes, "Direct Selection Tool")); + // Screen readers hear how to open the group with the search field's description. + let said: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::TextInput).filter_map(|n| n.description()).collect(); + assert!(said.iter().any(|d| d.ends_with(", In the Direct Selection Tool group: press and hold to open it")), "{said:?}"); + let callout = callout.expect("a box"); + assert!(callout.left() > outlined.right(), "right of a toolbar docked left: {callout:?} {outlined:?}"); + window.app.select_tool("groupSelection"); + let nodes = window.search("group selection tool"); + let (outlined, _, text) = window.callout().unwrap_or_else(|| panic!("a callout: {:?} {:?}", labels(&nodes), window.popup())); + assert_eq!(text, "Group Selection Tool"); + assert_eq!(outlined, bounds_of(&nodes, "Group Selection Tool")); + // Docked right, the box goes on its left. The Zoom Tool's slot is below the popup. + window.app.ui.toolbar_right = true; + window.frame(vec![]); + let nodes = window.search("zoom tool"); + assert_eq!(window.highlighted(), "tool:zoom"); + let (outlined, callout, text) = window.callout().unwrap_or_else(|| panic!("a callout: {:?} {:?}", labels(&nodes), window.popup())); + assert_eq!(text, "Zoom Tool"); + assert!(!window.popup().intersects(outlined), "{outlined:?} {:?}", window.popup()); + let callout = callout.expect("a box"); + assert!(callout.right() < outlined.left(), "left of a toolbar docked right: {callout:?} {outlined:?}"); + } + + /// A shown toolbar made with New Toolbar called Drawing that floats at `pos` and holds the Pen + /// Tool and the Curvature Tool in one group. + fn drawing_toolbar(pos: [f32; 2]) -> crate::state::CustomToolbar { + crate::state::CustomToolbar { + name: "Drawing".into(), + slots: vec![vec!["pen".into(), "curvature".into()]], + shown: true, + pos, + dock: None, + dock_right: false, + slot_tool: Default::default(), + double: false, + floating: vec![], + } + } + + /// With the Tools panel hidden, a shown toolbar made with New Toolbar that holds the tool gets + /// the outline; a group torn off it into a strip has the tool's own button outlined. + #[test] + fn a_tool_on_a_toolbar_made_with_new_toolbar_is_outlined_there() { + let mut window = Window::new(); + window.app.ui.toolbar = false; + window.app.ui.custom_toolbars.push(drawing_toolbar([100.0, 200.0])); + let nodes = window.search("pen tool"); + assert_eq!(window.highlighted(), "tool:pen"); + let (outlined, callout, text) = window.callout().expect("a callout"); + assert_eq!(text, "Pen Tool"); + assert!(callout.is_some()); + assert_eq!(outlined, bounds_of(&nodes, "Pen Tool")); + assert!(outlined.left() >= 100.0, "on the toolbar made with New Toolbar: {outlined:?}"); + let bar = window.app.ui.custom_toolbars[0].name.clone(); + assert_eq!(tool_home(&window.app, "curvature"), format!("{bar}, in the Pen Tool group")); + // The group torn off into a strip. + window.app.ui.custom_toolbars[0] + .floating + .push(crate::state::FloatingFlyout { tools: vec!["pen".into(), "curvature".into()], pos: [600.0, 500.0] }); + window.frame(vec![]); + window.frame(vec![]); + let (outlined, _, text) = window.callout().expect("a callout"); + assert_eq!(text, "Pen Tool"); + assert!(outlined.left() >= 600.0 && outlined.top() >= 500.0, "on the strip: {outlined:?}"); + // The row's home names no group: the strip shows each tool on its own button. + assert_eq!(tool_home(&window.app, "curvature"), bar); + } + + /// A group torn off the Tools panel into a strip has the tool's own button on the strip + /// outlined, with the tool's name. + #[test] + fn a_strip_torn_off_the_tools_panel_is_pointed_at() { + let mut window = Window::new(); + let slot = crate::toolbar::slots(&window.app).into_iter().map(|(_, s)| s).find(|s| s.contains(&"groupSelection")).expect("the group"); + let tools = slot.iter().map(|t| t.to_string()).collect(); + window.app.ui.floating_flyouts.push(crate::state::FloatingFlyout { tools, pos: [600.0, 500.0] }); + window.frame(vec![]); + window.search("group selection tool"); + assert_eq!(window.highlighted(), "tool:groupSelection"); + let (outlined, callout, text) = window.callout().expect("a callout"); + assert_eq!(text, "Group Selection Tool"); + assert!(callout.is_some()); + assert!(outlined.left() >= 600.0 && outlined.top() >= 500.0, "on the strip: {outlined:?}"); + // The row's home names no group: the strip shows each tool on its own button. + assert_eq!(tool_home(&window.app, "groupSelection"), "Toolbar"); + } + + /// Two viewports that note controls in turn keep one pass each in the list, whichever noted + /// first, also after one of them stops noting controls. + #[test] + fn the_noted_controls_hold_one_pass_per_viewport() { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(10.0, 10.0)); + let spot = |viewport: egui::ViewportId, pass: u64| Spot { + at: SpotAt::Menu("File".into()), + viewport, + pass, + layer: egui::LayerId::background(), + clip: rect, + rect, + }; + let (a, b) = (egui::ViewportId::ROOT, egui::ViewportId::from_hash_of("another window")); + let mut list = Vec::new(); + for pass in 0..20 { + for _ in 0..3 { + add_spot(&mut list, spot(a, pass)); + } + for _ in 0..2 { + add_spot(&mut list, spot(b, pass)); + } + assert_eq!(list.len(), 5, "pass {pass}"); + assert!(list.iter().all(|s| s.pass == pass), "pass {pass}"); + } + // The other window stops noting controls. + for pass in 20..40 { + for _ in 0..3 { + add_spot(&mut list, spot(a, pass)); + } + assert_eq!(list.len(), 5, "pass {pass}"); + } + } + + /// Beside a button, the box's text wraps to at most three rows to fit between the button and + /// the popup; with no popup beside it, it is one row. + #[test] + fn a_box_beside_a_button_wraps_to_fit_beside_the_popup() { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut checked = false; + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx(); + let rect = egui::Rect::from_min_size(egui::pos2(20.0, 100.0), egui::vec2(28.0, 28.0)); + let place = Spot { at: SpotAt::Slot(None, vec![]), viewport: ctx.viewport_id(), pass: 0, layer: ui.layer_id(), clip: screen, rect }; + let popup = egui::Rect::from_min_size(egui::pos2(rect.right() + 150.0, 50.0), egui::vec2(400.0, 300.0)); + let text = "In the Direct Selection Tool group: press and hold to open it"; + let (boxed, galley) = callout_box(ctx, &place, text, Some(popup)); + assert!((2..=BOX_ROWS).contains(&galley.rows.len()), "{} rows", galley.rows.len()); + assert!(boxed.left() > rect.right() && boxed.right() <= popup.left(), "{boxed:?} {popup:?}"); + let (_, one) = callout_box(ctx, &place, text, None); + assert_eq!(one.rows.len(), 1); + checked = true; + }); + out.textures_delta.clear(); + assert!(checked); + } + + /// The box never covers the button it points at: in a narrow window it wraps to fit between + /// the button and the window's edge, and where it cannot, only the outline is drawn and the + /// footer shows the text. + #[test] + fn the_box_keeps_off_its_button() { + let text = "In the Direct Selection Tool group: press and hold to open it"; + let check = |width: f32, left: f32| { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0)); + let mut how = None; + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx(); + let rect = egui::Rect::from_min_size(egui::pos2(left, 100.0), egui::vec2(28.0, 28.0)); + let place = Spot { at: SpotAt::Slot(None, vec![]), viewport: ctx.viewport_id(), pass: 0, layer: ui.layer_id(), clip: screen, rect }; + let aimed = aim(ctx, None, &place, text); + if aimed == Aim::Box { + let (boxed, _) = callout_box(ctx, &place, text, None); + assert!(!boxed.intersects(rect) && screen.contains_rect(boxed), "{boxed:?} {rect:?}"); + } + how = Some(aimed); + }); + out.textures_delta.clear(); + how + }; + assert_eq!(check(400.0, 180.0), Some(Aim::Box)); + assert_eq!(check(400.0, 192.0), Some(Aim::Box)); + assert_eq!(check(180.0, 60.0), Some(Aim::Outline)); + } + + /// The callout never covers the palette: a button under the popup is not pointed at, and a + /// button whose box would cover the popup is outlined with its text in the footer. + #[test] + fn the_callout_stays_off_the_palette() { + let mut window = Window::new(); + window.app.ui.toolbar = false; + window.app.ui.custom_toolbars.push(drawing_toolbar([600.0, 120.0])); + let nodes = window.search("pen tool"); + assert_eq!(window.highlighted(), "tool:pen"); + assert!(window.popup().contains(egui::pos2(620.0, 140.0)), "the toolbar is under the popup: {:?}", window.popup()); + assert_eq!(window.callout(), None); + // The toolbar is shown, under the popup: the footer names it and does not say it is hidden. + let footer = window.popup_labels(&nodes); + assert!(footer.contains(&"Drawing".to_string()), "{footer:?}"); + assert!(!footer.iter().any(|l| l.contains("not shown now")), "{footer:?}"); + // Left of the popup, with the box's place to its right on the popup. + let popup = window.popup(); + window.app.ui.custom_toolbars[0].pos = [popup.left() - 60.0, popup.top() + 30.0]; + window.frame(vec![]); + let nodes = window.frame(vec![]); + let (outlined, callout, text) = window.callout().expect("a callout"); + assert!(!popup.intersects(outlined), "{outlined:?} {popup:?}"); + assert_eq!((callout, text.as_str()), (None, "Pen Tool")); + assert!(labels(&nodes).contains(&"Pen Tool".to_string()), "{:?}", labels(&nodes)); + } + + /// In the pass where more results make the popup taller and it now covers the button, the + /// callout is checked against the popup's new size, and the next pass's footer names the home. + #[test] + fn the_callout_keeps_off_a_popup_that_grew_in_the_same_pass() { + let mut window = Window::new(); + window.app.ui.toolbar = false; + window.app.ui.custom_toolbars.push(drawing_toolbar([100.0, 120.0])); + window.search("pen tool"); + let small = window.popup(); + window.app.ui.custom_toolbars[0].pos = [small.center().x, small.bottom() + 2.0]; + window.frame(vec![]); + window.frame(vec![]); + assert_eq!(window.highlighted(), "tool:pen"); + let (outlined, ..) = window.callout().expect("a callout below the popup"); + window.app.ui.palette_query = "pen".into(); + window.frame(vec![]); + assert_eq!(window.highlighted(), "tool:pen"); + assert!(window.popup().intersects(outlined), "the popup grew over the button: {:?} {outlined:?}", window.popup()); + assert_eq!(window.callout(), None); + let nodes = window.frame(vec![]); + let footer = window.popup_labels(&nodes); + assert!(footer.contains(&"Drawing".to_string()), "{footer:?}"); + assert!(!footer.iter().any(|l| l.contains("not shown now")), "{footer:?}"); + } + + /// No callout where no control in view shows the home: in Presentation Mode, with the Tools + /// panel hidden, and for a command with no menu item. The footer says where it lives. + #[test] + fn a_home_out_of_view_is_named_in_the_footer() { + let mut window = Window::new(); + window.app.ui.screen_mode = 3; + let nodes = window.search("pen tool"); + assert_eq!(window.highlighted(), "tool:pen"); + assert_eq!(window.callout(), None); + assert!(labels(&nodes).contains(&"Toolbar, not shown now".to_string()), "{:?}", labels(&nodes)); + window.app.ui.screen_mode = 0; + window.app.ui.toolbar = false; + let nodes = window.search("pen tool"); + assert_eq!(window.callout(), None); + assert!(labels(&nodes).contains(&"Toolbar, not shown now".to_string()), "{:?}", labels(&nodes)); + // Toolbars hidden with Tab. + window.app.ui.toolbar = true; + window.app.run("window.dock", serde_json::json!({})).expect("Tab"); + assert!(window.app.ui.tab_hid.is_some()); + let nodes = window.search("pen tool"); + assert_eq!(window.highlighted(), "tool:pen"); + assert_eq!(window.callout(), None); + assert!(labels(&nodes).contains(&"Toolbar, not shown now".to_string()), "{:?}", labels(&nodes)); + window.app.run("window.dock", serde_json::json!({})).expect("Tab"); + assert!(window.app.ui.tab_hid.is_none() && window.app.ui.toolbar); + let entries = entries(&window.ctx, Lang::EN); + let none = entries.iter().find(|e| e.home.is_none() && !e.id.starts_with("tool:") && e.shortcut.is_empty()).expect("no menu item"); + let nodes = window.search(&none.id); + assert_eq!(window.highlighted(), none.id); + assert_eq!(window.callout(), None); + assert!(labels(&nodes).contains(&"No menu item".to_string()), "{:?}", labels(&nodes)); + // With a shortcut, the footer gives it. + let keyed = entries.iter().find(|e| e.home.is_none() && !e.id.starts_with("tool:") && !e.shortcut.is_empty()).expect("a shortcut"); + let nodes = window.search(&keyed.id); + assert_eq!(window.highlighted(), keyed.id); + assert_eq!(window.callout(), None); + let line = format!("No menu item, {}", menus::shown_shortcut(&keyed.shortcut)); + assert!(labels(&nodes).contains(&line), "{line} in {:?}", labels(&nodes)); + } + + /// In the pass that opens the palette, the menu bar and the toolbars have noted no control yet: + /// the footer does not call a home that is in view "not shown now", and the next pass points + /// at it. + #[test] + fn the_pass_that_opens_the_palette_names_no_home_as_hidden() { + let mut window = Window::new(); + // Opened once and closed, the popup has its size, so the pass that opens it again draws + // it. One pass a frame, so the frame shows that pass. + window.search("pen tool"); + window.app.ui.palette_open = false; + window.frame(vec![]); + window.ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::MIN); + window.app.ui.palette_open = true; + let nodes = window.frame(vec![]); + assert_eq!(window.highlighted(), "tool:pen"); + let footer = window.popup_labels(&nodes); + assert!(!footer.is_empty(), "the popup is drawn: {:?}", labels(&nodes)); + assert!(!footer.iter().any(|l| l.contains("not shown now")), "{footer:?}"); + window.frame(vec![]); + assert!(window.callout().is_some()); + } + + /// Moving the pointer onto a row moves the callout to that result's home in the same frame. + #[test] + fn the_callout_follows_the_pointer() { + let mut window = Window::new(); + let nodes = window.search("select"); + let entries = entries(&window.ctx, Lang::EN); + let x = window.popup().center().x; + let target = rows(&nodes) + .into_iter() + .filter(|r| !r.1) + .find_map(|r| { + let e = entries.iter().find(|e| row_label(e, &home_text(&window.app, e)) == r.0)?; + let path = e.home.as_ref().filter(|_| !e.id.starts_with("tool:") && !e.menu_item.is_empty())?; + Some((e.id.clone(), format!("{path} › {}", e.menu_item), (r.2 + r.3) / 2.0)) + }) + .expect("a row with a menu item"); + let (id, text, y) = target; + window.frame(vec![egui::Event::PointerMoved(egui::pos2(x, y as f32 - 3.0))]); + window.frame(vec![egui::Event::PointerMoved(egui::pos2(x, y as f32))]); + assert_eq!(window.highlighted(), id); + assert_eq!(window.callout().map(|c| c.2), Some(text)); + } + + /// Down moves the callout to the next result's home in the same frame, and moving the + /// highlight changes no toolbar, flyout, drawer or tool. + #[test] + fn the_callout_follows_the_highlight_and_reveals_nothing() { + let mut window = Window::new(); + window.search("select"); + let before = (window.app.ui.flyout, window.app.ui.tools_drawer, window.app.ui.toolbar, window.app.session.tool_id()); + let entries = entries(&window.ctx, Lang::EN); + for _ in 0..6 { + let key = + egui::Event::Key { key: egui::Key::ArrowDown, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + window.frame(vec![key]); + let id = window.highlighted(); + let e = entries.iter().find(|e| e.id == id).unwrap(); + let callout = window.callout(); + if let Some(path) = e.home.as_ref().filter(|_| !id.starts_with("tool:")) { + assert_eq!(callout.map(|c| c.2), Some(format!("{path} › {}", e.menu_item)), "{id}"); + } + assert!(window.app.ui.learn_locate.is_none()); + } + let after = (window.app.ui.flyout, window.app.ui.tools_drawer, window.app.ui.toolbar, window.app.session.tool_id()); + assert_eq!(before, after); + } + + /// Every catalog translates the callout's and the footer's words. + #[test] + fn catalogs_translate_the_callout_words() { + let words = ["In the menu bar: {path}", "In the {group} group: press and hold to open it", "{home}, not shown now"]; + let missing: Vec = Lang::all() + .filter(|l| *l != Lang::EN) + .flat_map(|l| words.iter().filter(move |w| !crate::i18n::has(l, w)).map(move |w| format!("{}: {w}", l.code()))) + .collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + + /// A control noted in an earlier pass, in another viewport or clipped by its scroll area is not + /// pointed at; the box stays inside a narrow window. + #[test] + fn only_a_control_in_view_in_this_pass_is_pointed_at() { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0)); + let mut checked = false; + for _ in 0..2 { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx(); + let pass = ctx.cumulative_pass_nr_for(ctx.viewport_id()); + let rect = egui::Rect::from_min_size(egui::pos2(270.0, 10.0), egui::vec2(28.0, 28.0)); + let at = |name: &str| SpotAt::Menu(name.into()); + let spot = |name: &str, viewport, pass, clip| Spot { at: at(name), viewport, pass, layer: ui.layer_id(), clip, rect }; + let list = vec![ + spot("old", ctx.viewport_id(), pass.wrapping_sub(1), screen), + spot("other", egui::ViewportId::from_hash_of("detached"), pass, screen), + spot("clipped", ctx.viewport_id(), pass, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(280.0, 200.0))), + spot("shown", ctx.viewport_id(), pass, screen), + ]; + ctx.data_mut(|d| d.insert_temp(spots_id(), list)); + for name in ["old", "other", "clipped"] { + assert!(super::spot(ctx, |a| *a == at(name)).is_none(), "{name}"); + } + let shown = super::spot(ctx, |a| *a == at("shown")).expect("shown"); + let text = "Effect › Stylize › Round Corners… and a long tail of words"; + let r = callout(ctx, &Spot { at: SpotAt::Slot(None, vec![]), ..shown.clone() }, Some(text), None).unwrap(); + assert!(screen.contains_rect(r), "{r:?}"); + let r = callout(ctx, &shown, Some(text), None).unwrap(); + assert!(screen.contains_rect(r), "{r:?}"); + checked = true; + }); + out.textures_delta.clear(); + } + assert!(checked); + } + + /// A control under a window drawn above its layer is not pointed at; with the window moved off + /// it, it is. + #[test] + fn a_control_under_a_window_is_not_pointed_at() { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let rect = egui::Rect::from_min_size(egui::pos2(20.0, 20.0), egui::vec2(28.0, 28.0)); + let at = || SpotAt::Menu("bar".into()); + for (cover_at, pointed) in [(egui::pos2(10.0, 10.0), false), (egui::pos2(200.0, 150.0), true)] { + let mut seen = None; + // The second pass sees both areas laid out. + for _ in 0..2 { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx().clone(); + ctx.data_mut(|d| d.insert_temp(spots_wanted_id(), true)); + egui::Area::new(egui::Id::unique("test-toolbar")).order(egui::Order::Middle).fixed_pos(egui::Pos2::ZERO).show(&ctx, |ui| { + ui.allocate_rect(rect, egui::Sense::hover()); + note_spot(ui, rect, at); + }); + egui::Area::new(egui::Id::unique("test-cover")).order(egui::Order::Middle).fixed_pos(cover_at).show(&ctx, |ui| { + ui.allocate_space(egui::vec2(80.0, 80.0)); + }); + seen = Some(super::spot(&ctx, |a| *a == at()).is_some()); + }); + out.textures_delta.clear(); + } + assert_eq!(seen, Some(pointed), "{cover_at:?}"); + } + } } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index e20d75e610..d87cf4c182 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -11,27 +11,49 @@ use crate::menus; const INDEX_CHARS: usize = 200; /// The field of a result a word comes from, best first, and the fields of the English stem forms -/// ([`stems`]) of the words of the label and the menu path. +/// ([`stems`]) of the words of the label, the menu path and the description ([`description`]). const LABEL: u8 = 0; const PATH: u8 = 1; const ID: u8 = 2; const LABEL_STEMMED: u8 = 3; const PATH_STEMMED: u8 = 4; +const DESCRIPTION: u8 = 5; +const DESCRIPTION_STEMMED: u8 = 6; /// A word's grade in a result, best first: a whole word of the label, a word of the label it /// shares an English stem form with ("outlines" and Outline), a word of the label it starts, a -/// word of the menu path it is, shares a stem form with or starts, a word of the id it is or -/// starts, or text inside a word of any field ([`super::matching`]'s substring rule). The grades -/// without a stem are twice the values they had before stems were added, so results matched -/// without a stem keep their order by the sum of the grades. +/// word of the label with the same meaning ([`super::words`]), a word of the menu path it is, +/// shares a stem form with or starts, a word of the menu path with the same meaning, a word of the +/// id it is or starts, text inside a word of any field ([`super::matching`]'s substring rule), a +/// word of the description it is, shares a stem form with, starts or means the same as, a word of +/// the label a typo away from it ([`Index::typos`]), or a word of the menu path a typo away. A word +/// of the description comes after the substring rule, so every result the substring rule finds +/// ranks above a result found only by its description. The grades without a stem or a word with +/// the same meaning are twice the values they had before those were added, so results matched +/// without them keep their order by the sum of the grades. const LABEL_WORD: u8 = 2; const LABEL_STEM: u8 = 3; const LABEL_PREFIX: u8 = 4; +const LABEL_SYNONYM: u8 = 5; const PATH_WORD: u8 = 6; +const PATH_SYNONYM: u8 = 7; const ID_WORD: u8 = 8; const SUBSTRING: u8 = 10; +const DESCRIPTION_WORD: u8 = 11; +const LABEL_TYPO: u8 = 12; +const PATH_TYPO: u8 = 14; const NONE: u8 = u8::MAX; +/// The most characters of a command's description the index reads (VectorCraft's own limit). +const DESCRIPTION_CHARS: usize = 300; + +/// The words of a description the index leaves out, besides words of 2 characters or fewer and +/// words with no letter. +const STOP_WORDS: &[&str] = &["the", "and", "ids", "true", "false", "null"]; + +/// The most words a query word with a typo meets ([`Index::typos`]), nearest first. +const TYPO_TERMS: usize = 32; + /// How a whole query matches a result, best first: it is the result's id, it is a label, a label /// starts with it, or it is the initials of a label. const EXACT_ID: u8 = 0; @@ -62,6 +84,38 @@ pub(crate) struct Index { initials_text: String, /// Each result's offset and length in `initials_text`. initials: Vec<(u32, u16)>, + /// Each word of a group of words with the same meaning ([`super::words::GROUPS`], and the + /// words the UI language's catalog adds), with the group's place in the table. + synonyms: HashMap, u16>, +} + +/// Is `w` one word as the index splits text ([`words`])? +pub(crate) fn is_one_word(w: &str) -> bool { + let mut it = words(w); + it.next() == Some(w) && it.next().is_none() +} + +/// The words of each group of [`super::words::GROUPS`], with the words `search_row` gives for the +/// group's catalog row ([`super::words::row_key`]) in the UI language. A word the catalog gives +/// that is not a single word, or that is already a word of a group, is left out. +fn synonym_groups(search_row: impl Fn(&str) -> Option) -> HashMap, u16> { + let mut out: HashMap, u16> = HashMap::new(); + let groups = super::words::GROUPS.iter().enumerate().filter_map(|(g, words)| u16::try_from(g).ok().map(|g| (g, words))); + for (g, words) in groups.clone() { + for &w in *words { + out.insert(w.into(), g); + } + } + for (g, words) in groups { + let Some(text) = search_row(&super::words::row_key(words)) else { continue }; + for (w, single) in super::words::row_words(&text) { + if single { + out.entry(w.into()).or_insert(g); + } + } + } + out.shrink_to_fit(); + out } /// Splits `text` into lowercase words at whitespace and at `.`, `-`, `/`, `(`, `)`, `…`, `›`, `,` @@ -133,6 +187,80 @@ fn stems(word: &str) -> Vec { vec![] } +/// Is `c` a letter of a script written without spaces between words (Han, kana or Hangul)? +fn spaceless(c: char) -> bool { + matches!( + u32::from(c), + 0x1100..=0x11FF + | 0x3040..=0x30FF + | 0x3130..=0x318F + | 0x31F0..=0x31FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xA960..=0xA97F + | 0xAC00..=0xD7FF + | 0xF900..=0xFAFF + | 0xFF66..=0xFFDC + | 0x20000..=0x323AF + ) +} + +/// The most edits a query word may be away from a word it meets as a typo: 1 for a word of 4 to 7 +/// characters, 2 for a longer one, and none for a shorter word or one with letters of a script +/// written without spaces ([`spaceless`]). +fn typo_bound(word: &str) -> Option { + if word.chars().any(spaceless) { + return None; + } + match word.chars().count() { + 0..=3 => None, + 4..=7 => Some(1), + _ => Some(2), + } +} + +/// The number of edits between `a` and `b` when it is at most `bound`: a character inserted, +/// removed or changed, or two adjacent characters swapped (`gruop` and `group`), each count as one. +/// The count stops as soon as every way of lining the two up needs more than `bound`. +fn edits_within(a: &[char], b: &[char], bound: usize) -> Option { + if a.len().abs_diff(b.len()) > bound { + return None; + } + let at = |row: &[usize], j: usize| row.get(j).copied().unwrap_or(usize::MAX); + // The edits between the first i characters of `a` and the first j of `b`, for the rows i - 2, + // i - 1 and i. + let mut before: Vec = vec![0; b.len() + 1]; + let mut last: Vec = (0..=b.len()).collect(); + let mut row: Vec = vec![0; b.len() + 1]; + for (i, &ca) in a.iter().enumerate() { + if let Some(first) = row.first_mut() { + *first = i + 1; + } + for (j, &cb) in b.iter().enumerate() { + let changed = at(&last, j).saturating_add(usize::from(ca != cb)); + let removed = at(&last, j + 1).saturating_add(1); + let inserted = at(&row, j).saturating_add(1); + let mut edits = changed.min(removed).min(inserted); + let swapped = i.checked_sub(1).and_then(|k| a.get(k)).zip(j.checked_sub(1).and_then(|k| b.get(k))); + if let Some((&pa, &pb)) = swapped + && pa == cb + && pb == ca + { + edits = edits.min(at(&before, j - 1).saturating_add(1)); + } + if let Some(cell) = row.get_mut(j + 1) { + *cell = edits; + } + } + if row.iter().all(|&e| e > bound) { + return None; + } + std::mem::swap(&mut before, &mut last); + std::mem::swap(&mut last, &mut row); + } + last.last().copied().filter(|&e| e <= bound) +} + /// Adds each word of `text` to `found` for result `entry` in `field`, and with `stemmed`, each /// word's English stem forms in that field. fn add_words(found: &mut Vec<(String, u16, u8)>, text: &str, entry: u16, field: u8, stemmed: Option) { @@ -152,6 +280,50 @@ fn split_name(name: &str) -> (&str, &str) { } } +/// A command's description, read from its params text: the text without each `{…}` group that is +/// not inside a `{`, `[` or `(` group (braces inside double quotes are text), without each such +/// `[…]` or `(…)` group just after a `→`, and without the `→` just before a removed group, with +/// each run of whitespace made one space and cut to its first [`DESCRIPTION_CHARS`] characters at +/// the end of a word. A group that is never closed stays in the text, and so does a result written +/// as words after a `→`. Params text that is only a group has an empty description. +pub(crate) fn description(params: &str) -> String { + let mut out = String::new(); + // The end of the text copied to `out`, and whether a removed group is open. + let (mut copied, mut open) = (0, false); + for (i, ch, depth) in crate::shortcut_editor::outside_quotes(params) { + let before = params.get(copied..i).unwrap_or_default(); + match ch { + '{' | '[' | '(' if depth == 0 && (ch == '{' || before.trim_end().ends_with('→')) => { + out.push_str(before); + (copied, open) = (i, true); + } + '}' | ']' | ')' if depth == 1 && open => { + let kept = out.trim_end().strip_suffix('→').unwrap_or(&out).len(); + out.truncate(kept); + out.push(' '); + (copied, open) = (i + ch.len_utf8(), false); + } + _ => {} + } + } + out.push_str(params.get(copied..).unwrap_or_default()); + let text = out.split_whitespace().collect::>().join(" "); + // A cut inside a word drops the rest of that word, so no part of a word is read as a word. + let Some((head, rest)) = text.char_indices().nth(DESCRIPTION_CHARS).and_then(|(end, _)| text.split_at_checked(end)) else { return text }; + let head = if rest.starts_with(' ') { head } else { head.rsplit_once(' ').map_or("", |(kept, _)| kept) }; + head.trim_end().to_string() +} + +/// The lowercase words of the lowercased `description` the index holds: split at every character +/// that is not a letter, a digit or an apostrophe, without apostrophes at either end, and leaving +/// out words of 2 characters or fewer, words with no letter and [`STOP_WORDS`]. +fn description_words(description: &str) -> impl Iterator { + description + .split(|c: char| !(c.is_alphanumeric() || c == '\'')) + .map(|w| w.trim_matches('\'')) + .filter(|w| w.chars().count() > 2 && w.chars().any(char::is_alphabetic) && !STOP_WORDS.contains(w)) +} + /// `name` without the id that follows it when the result shows its id. fn without_id<'a>(name: &'a str, id: &str) -> &'a str { name.strip_suffix(')').and_then(|n| n.strip_suffix(id)).and_then(|n| n.strip_suffix(" (")).unwrap_or(name) @@ -172,9 +344,12 @@ impl Index { /// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The /// words of a result's menu home and of its menu item's label count as menu path words. The /// words of the English names, menu home and menu item label also add their English stem forms - /// ([`stems`]); words in the UI language do not. A catalog with more results than a posting can - /// name gets an empty index, and queries match by the substring rule alone. - pub(crate) fn build(entries: &[Entry], homes: &[Option]) -> Index { + /// ([`stems`]); words in the UI language do not. `params` gives each result's params text, whose + /// [`description`] adds its words ([`description_words`]) and their stem forms; only the words + /// are kept. `search_row` gives the UI language's words for a group of words with the same + /// meaning ([`synonym_groups`]). A catalog with more results than a posting can name gets an + /// empty index, and queries match by the substring rule alone. + pub(crate) fn build(entries: &[Entry], homes: &[Option], params: &[&str], search_row: impl Fn(&str) -> Option) -> Index { if entries.len() > usize::from(u16::MAX) { return Index::default(); } @@ -211,12 +386,18 @@ impl Index { for id in ids(e) { found.extend(words(id).map(|w| (w.to_string(), entry, ID))); } + if let Some(text) = params.get(i).filter(|p| !p.is_empty()) { + for w in description_words(&description(text).to_lowercase()) { + found.push((w.to_string(), entry, DESCRIPTION)); + found.extend(stems(w).into_iter().map(|s| (s, entry, DESCRIPTION_STEMMED))); + } + } let len = u16::try_from(initials_text.len() - start).unwrap_or(0); initials.push((u32::try_from(start).unwrap_or(0), len)); } found.sort_unstable(); found.dedup(); - let mut index = Index { initials_text, initials, ..Index::default() }; + let mut index = Index { initials_text, initials, synonyms: synonym_groups(search_row), ..Index::default() }; let mut last: Option<&str> = None; for (word, entry, field) in &found { if last != Some(word.as_str()) { @@ -253,6 +434,8 @@ impl Index { + self.postings.capacity() * std::mem::size_of::() + self.initials_text.capacity() + self.initials.capacity() * std::mem::size_of::<(u32, u16)>() + + self.synonyms.capacity() * (std::mem::size_of::<(Box, u16)>() + 1) + + self.synonyms.keys().map(|w| w.len()).sum::() } /// The text of the word at `(offset, len)` in `term_text`. @@ -273,10 +456,11 @@ impl Index { self.terms.binary_search_by(|t| self.text(t).cmp(text)).ok() } - /// The best grade ([`LABEL_WORD`] to [`ID_WORD`]) `word` gets in each result, [`NONE`] where it - /// is no word, shares no English stem form with a word of the label or menu path, and starts no - /// word of the result. The words it starts are found by a binary search of the sorted words; a - /// stem form matches only a word or stem form equal to it. + /// The best grade ([`LABEL_WORD`] to [`DESCRIPTION_WORD`], without [`SUBSTRING`]) `word` gets in + /// each result, [`NONE`] where it is no word, shares no English stem form with a word of the + /// label, menu path or description, means the same as none of them, and starts no word of the + /// result. The words it starts are found by a binary search of the sorted words; a stem form + /// matches only a word or stem form equal to it. fn grades(&self, word: &str, n: usize) -> Vec { let mut out = vec![NONE; n]; let mut mark = |postings: &[Posting], grade: &dyn Fn(u8) -> Option| { @@ -301,19 +485,22 @@ impl Index { LABEL if whole => Some(LABEL_WORD), LABEL => Some(LABEL_PREFIX), PATH => Some(PATH_WORD), + DESCRIPTION => Some(DESCRIPTION_WORD), ID => Some(ID_WORD), _ => None, }); } // The word meets a stem form of a word of the result ("scale" and Scaling) when it is itself - // a word of some result, so a partly typed word ("scal") that only equals a stem form does - // not lift Scaling above Scale. + // a word of some result's label, menu path, id or description, so a partly typed word + // ("scal") that only equals a stem form does not lift Scaling above Scale. A description is + // cut at the end of a word ([`description`]), so it holds no partly typed word. if let Some(t) = self.find(word) - && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH | ID)) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH | ID | DESCRIPTION)) { mark(self.postings_of(t), &|field| match field { LABEL_STEMMED => Some(LABEL_STEM), PATH_STEMMED => Some(PATH_WORD), + DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), _ => None, }); } @@ -324,12 +511,88 @@ impl Index { mark(self.postings_of(t), &|field| match field { LABEL | LABEL_STEMMED => Some(LABEL_STEM), PATH | PATH_STEMMED => Some(PATH_WORD), + DESCRIPTION | DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), + _ => None, + }); + } + // Each other word of the word's group of words with the same meaning ([`Index::synonyms_of`]) + // meets a word of the label, menu path or description, or a stem form of one, equal to it. + // Ids are not matched this way. + for t in self.synonyms_of(word) { + mark(self.postings_of(t), &|field| match field { + LABEL | LABEL_STEMMED => Some(LABEL_SYNONYM), + PATH | PATH_STEMMED => Some(PATH_SYNONYM), + DESCRIPTION | DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), _ => None, }); } out } + /// The other words of the group of words with the same meaning that `word`, or a stem form of + /// it, is in ("bg" and background, "flipped" and reflect), as places in `terms`; the words of the + /// group no result holds are left out. + fn synonyms_of(&self, word: &str) -> Vec { + let group = std::iter::once(word.to_string()).chain(stems(word)).find_map(|w| self.synonyms.get(w.as_str()).copied()); + let Some(group) = group else { return vec![] }; + let mut found: Vec = self.synonyms.iter().filter(|&(w, &g)| g == group && &**w != word).filter_map(|(w, _)| self.find(w)).collect(); + // The map's order changes from one build to the next; the words' order in `terms` does not. + found.sort_unstable(); + found + } + + /// The words of labels and menu paths that `word` is a typo of: within [`typo_bound`] edits of + /// it ([`edits_within`]), at most [`TYPO_TERMS`], nearest first, as places in `terms`. Ids and + /// words with letters of a script written without spaces ([`spaceless`]) are not compared. + fn typos(&self, word: &str) -> Vec { + let Some(bound) = typo_bound(word) else { return vec![] }; + let word: Vec = word.chars().collect(); + let mut term: Vec = vec![]; + let mut near: Vec<(usize, usize)> = vec![]; + for (t, at) in self.terms.iter().enumerate() { + let text = self.text(at); + if text.chars().count().abs_diff(word.len()) > bound || text.chars().any(spaceless) { + continue; + } + term.clear(); + term.extend(text.chars()); + if let Some(edits) = edits_within(&word, &term, bound) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH)) + { + near.push((edits, t)); + } + } + near.sort_unstable(); + near.truncate(TYPO_TERMS); + near.into_iter().map(|(_, t)| t).collect() + } + + /// Gives each result a word of `near` ([`Index::typos`]) is a word of its label or menu path + /// [`LABEL_TYPO`] or [`PATH_TYPO`] in `grades`, where its grade is not better. A typo replaces + /// [`DESCRIPTION_WORD`], since a result found only by its description ranks below one found + /// through a typo ([`rank`]). + fn mark_typos(&self, near: &[usize], grades: &mut [u8]) { + for &t in near { + for p in self.postings_of(t) { + let grade = match p.field { + LABEL => LABEL_TYPO, + PATH => PATH_TYPO, + _ => continue, + }; + if let Some(g) = grades.get_mut(usize::from(p.entry)) { + *g = if *g == DESCRIPTION_WORD { grade } else { (*g).min(grade) }; + } + } + } + } + + /// The text of the first word of `near` that is a word of result `i` in one of `fields` (its + /// label or its menu path, and their stem forms). + fn nearest_of(&self, near: &[usize], i: usize, fields: &[u8]) -> Option<&str> { + let t = near.iter().find(|&&t| self.postings_of(t).iter().any(|p| usize::from(p.entry) == i && fields.contains(&p.field)))?; + self.terms.get(*t).map(|at| self.text(at)) + } + /// Is `query` (no spaces) the initials of one of result `i`'s labels? fn initials_are(&self, i: usize, query: &str) -> bool { let Some(&(offset, len)) = self.initials.get(i) else { return false }; @@ -379,18 +642,29 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { NO_PHRASE } -/// What results are ordered by, compared field by field: how the whole query matches, the worst -/// grade a word gets, the sum of the grades, the kind of result and the label's length. -type RankKey = (u8, u8, u32, u8, usize); +/// What results are ordered by, compared field by field: whether a word matched only through a +/// description, whether a word matched only through a typo, how the whole query matches, the worst +/// grade a word gets, the sum of the grades, how the whole query matches when read with the words +/// of the same meaning it matched through, the kind of result and the label's length. +type RankKey = (bool, bool, u8, u8, u32, u8, u8, usize); /// The results of `entries` that the lowercased `query` matches, best first, as places in /// `entries`. A result matches when every word of the query is text in one of its names or ids /// (the rule the palette always had, so nothing it found is lost), when every word of the query is -/// or starts a word of its label, menu path or id or shares an English stem form with a word of its -/// label or menu path ("rounded corners" for Round Corners…), or when the query is the initials of -/// a label ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), -/// then by the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the -/// label's length and the catalog order. An empty query lists every result in catalog order. +/// or starts a word of its label, menu path, description ([`description`]) or id, shares an English +/// stem form with a word of its label, menu path or description ("rounded corners" for Round +/// Corners…) or means the same as a word of its label, menu path or description ("remove bg" for +/// Remove Background…), or when the query is the initials of a label ("ea" for Export As…). A query +/// word that is no word, stem form or word start of any result's label, menu path or id also +/// matches the words of labels and menu paths it is a typo of ([`Index::typos`]). +/// Results where a word matched only through a description come after every other result. Before +/// them, results where a word matched only through a typo come after every other result, and their +/// whole-query match is read with each such word replaced by the word it is a typo of ("gruop" as +/// "group"). Results are ordered by that, by how the whole query matches ([`phrase`]), then by the +/// worst grade a word gets, the sum of the grades, how the whole query matches when read with each +/// word matched through a word of the same meaning replaced by that word ("colour" as "color"), +/// the kind of result ([`kind`]), the label's length and the catalog order. An empty query lists +/// every result in catalog order. pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let query = normalize(query); if query.is_empty() { @@ -399,8 +673,39 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let spaced: Vec<&str> = query.split(' ').collect(); let head: String = query.chars().take(INDEX_CHARS).collect(); let tokens: Vec<&str> = words(&head).collect(); + // Where each word starts in the query (`head` is its start), for reading the query with a typo + // corrected. + let starts: Vec = tokens.iter().map(|t| (t.as_ptr() as usize).saturating_sub(head.as_ptr() as usize)).collect(); let n = entries.len(); - let indexed: Vec> = tokens.iter().map(|t| index.grades(t, n)).collect(); + let mut indexed: Vec> = Vec::with_capacity(tokens.len()); + let mut typos: Vec> = Vec::with_capacity(tokens.len()); + let mut meanings: Vec> = Vec::with_capacity(tokens.len()); + // After a word that is nothing in any result and a typo of nothing, a result is found only by + // the substring rule or its initials, where a typo grade changes nothing, so the later words are + // not compared. + let mut compare = true; + for (k, t) in tokens.iter().enumerate() { + // A repeated word is graded once. + if let Some(j) = tokens.iter().take(k).position(|u| u == t) + && let (Some(grades), Some(near), Some(same)) = (indexed.get(j).cloned(), typos.get(j).cloned(), meanings.get(j).cloned()) + { + indexed.push(grades); + typos.push(near); + meanings.push(same); + continue; + } + meanings.push(index.synonyms_of(t)); + let mut grades = index.grades(t, n); + // A word that matches only words of descriptions is still compared with the words of labels + // and menu paths it may be a typo of. + let near = if compare && grades.iter().all(|&g| g == NONE || g == DESCRIPTION_WORD) { index.typos(t) } else { vec![] }; + if near.is_empty() && grades.iter().all(|&g| g == NONE) { + compare = false; + } + index.mark_typos(&near, &mut grades); + indexed.push(grades); + typos.push(near); + } // The index reads only the start of a longer query, so such a query matches by the substring // rule, which reads all of it. let fits = query.chars().count() <= INDEX_CHARS; @@ -414,24 +719,80 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { // Each word's grade, the worst and their sum; with initials, every word counts as a word // the label starts, as the initials stand for every word of the label. let (mut all_indexed, mut worst, mut sum) = (fits && !tokens.is_empty(), 0u8, 0u32); - for (grades, token) in indexed.iter().zip(&tokens) { + // The query as read for the whole-query match, with each word matched only through a typo + // replaced by the word of this result it is a typo of; and as read with each word matched + // through a word with the same meaning replaced by that word too. + let (mut typo, mut corrected, mut copied) = (false, String::new(), 0); + let mut described = false; + let (mut synonym, mut meant, mut meant_copied) = (false, String::new(), 0); + let splice = |out: &mut String, copied: &mut usize, k: usize, token: &str, word: &str| { + if let Some(&start) = starts.get(k) + && let Some(between) = query.get(*copied..start) + { + out.push_str(between); + out.push_str(word); + *copied = start + token.len(); + } + }; + for (k, (grades, token)) in indexed.iter().zip(&tokens).enumerate() { let mut g = grades.get(i).copied().unwrap_or(NONE); if g == NONE { all_indexed = false; - if e.haystack.contains(token) { - g = SUBSTRING; + } + if g > SUBSTRING && e.haystack.contains(token) { + g = SUBSTRING; + } + let g = if initials { + g.min(LABEL_PREFIX) + } else if g == NONE { + SUBSTRING + } else { + g + }; + described |= g == DESCRIPTION_WORD; + let field = match g { + LABEL_TYPO => Some(LABEL), + PATH_TYPO => Some(PATH), + _ => None, + }; + if let Some(field) = field { + typo = true; + if let Some(near) = typos.get(k).and_then(|near| index.nearest_of(near, i, &[field])) { + splice(&mut corrected, &mut copied, k, token, near); + splice(&mut meant, &mut meant_copied, k, token, near); + } + } + let fields: &[u8] = match g { + LABEL_SYNONYM => &[LABEL, LABEL_STEMMED], + PATH_SYNONYM => &[PATH, PATH_STEMMED], + _ => &[], + }; + if !fields.is_empty() { + synonym = true; + if let Some(same) = meanings.get(k).and_then(|same| index.nearest_of(same, i, fields)) { + splice(&mut meant, &mut meant_copied, k, token, same); } } - let g = if initials { g.min(LABEL_PREFIX) } else { g.min(SUBSTRING) }; worst = worst.max(g); sum += u32::from(g); } if !(substring || all_indexed || initials) { continue; } - let tier = phrase(e, &query, initials); + let tier = if typo { + corrected.push_str(query.get(copied..).unwrap_or_default()); + phrase(e, &corrected, false) + } else { + phrase(e, &query, initials) + }; + let meant_tier = if synonym { + meant.push_str(query.get(meant_copied..).unwrap_or_default()); + phrase(e, &meant, false) + } else { + tier + }; let length = split_name(&e.shown).0.chars().count(); - ranked.push(((tier, worst, sum, e.kind, length), place)); + ranked.push(((described, typo, tier, worst, sum, meant_tier, e.kind, length), place)); } ranked.sort_by_key(|&(key, place)| (key, place)); ranked.into_iter().map(|(_, place)| place).collect() @@ -460,6 +821,10 @@ pub(crate) fn menu_homes(native: bool) -> HashMap { out.entry(key(id, p)).or_insert_with(|| (path.join(" › "), *label)); + // Window › Learn runs `window.learn`, which is a result of its own too. + if *id == "window.learn" { + out.entry((*id).to_string()).or_insert_with(|| (path.join(" › "), *label)); + } } menus::Item::Sub(name, children) => { path.push(name); @@ -510,12 +875,19 @@ mod tests { kind: kind(id, home.as_deref()), home, menu_item: "", + label_at: 0, + names_item: false, } } /// `entries` with their index. fn synthetic(entries: Vec) -> Catalog { - let index = Index::build(&entries, &[]); + described(entries, &[]) + } + + /// `entries` with their index, the params text of each in `params`. + fn described(entries: Vec, params: &[&str]) -> Catalog { + let index = Index::build(&entries, &[], params, |_| None); Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } } @@ -704,6 +1076,299 @@ mod tests { } } + /// Edits are counted up to a bound: a changed, inserted or removed character, or two adjacent + /// characters swapped, is one edit, and words further apart than the bound give none. + #[test] + fn edits_are_counted_up_to_a_bound() { + let edits = |a: &str, b: &str, bound: usize| edits_within(&a.chars().collect::>(), &b.chars().collect::>(), bound); + for (a, b, bound, expected) in [ + ("group", "group", 1, Some(0)), + ("gruop", "group", 1, Some(1)), + ("elipse", "ellipse", 1, Some(1)), + ("rectange", "rectangle", 2, Some(1)), + ("eyedroper", "eyedropper", 2, Some(1)), + ("recktanglee", "rectangle", 2, Some(2)), + ("grop", "group", 1, Some(1)), + ("grap", "group", 1, None), + ("ab", "abcd", 1, None), + ("ca", "abc", 2, None), + ("abcd", "wxyz", 2, None), + ("über", "uber", 1, Some(1)), + ("", "ab", 2, Some(2)), + ] { + assert_eq!(edits(a, b, bound), expected, "{a} {b}"); + assert_eq!(edits(b, a, bound), expected, "{b} {a}"); + } + assert_eq!(typo_bound("pen"), None); + assert_eq!(typo_bound("elip"), Some(1)); + assert_eq!(typo_bound("rectang"), Some(1)); + assert_eq!(typo_bound("rectange"), Some(2)); + for w in ["群組群組", "かなかなか", "한국어단어", "zz群組"] { + assert_eq!(typo_bound(w), None, "{w}"); + } + } + + /// A query word with a typo finds a result whose label or menu path holds the word, below every + /// result matched without a typo, and a word that is a word or a word start of some result, a + /// word of fewer than 4 letters, an id and a word of a script written without spaces get no + /// typo matches. + #[test] + fn a_word_with_a_typo_finds_the_result() { + let c = synthetic(vec![entry("Zz Group", "a.one"), entry("Zz Cut", "b.two"), entry("Zz Rectangle", "c.three")]); + assert_eq!(ranked(&c, "gruop"), ["a.one"], "two letters swapped"); + assert_eq!(ranked(&c, "gruop zz"), ["a.one"]); + assert_eq!(ranked(&c, "cutx"), ["b.two"]); + assert!(ranked(&c, "cux").is_empty(), "3 letters"); + assert_eq!(ranked(&c, "recktanglee"), ["c.three"], "two edits in a longer word"); + assert!(ranked(&c, "rectanglexxx").is_empty()); + // Below a result whose name holds the word as text, and below one that holds it whole. + let c = synthetic(vec![entry("Zz Color", "a.one"), entry("Zz Bcolrb", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"]); + let c = synthetic(vec![entry("Color", "a.one"), entry("Zz Bcolrb", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"], "also when the word spelled right is the label"); + let c = synthetic(vec![entry("Zz Color", "a.one"), entry("Zz Colr", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two"], "a word some result holds gets no typo matches"); + // A word of the label before a word of the menu path. + let c = synthetic(vec![entry("Color › Zz Other", "a.one"), entry("Zz Color", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"]); + // Ids and words of scripts written without spaces. + let c = synthetic(vec![entry("Zz One", "group.one"), entry("物件 › 群組群組", "b.two")]); + assert!(ranked(&c, "gruop").is_empty()); + assert!(ranked(&c, "群組群物").is_empty()); + // A word of Latin letters followed by Han letters, one edit from "abcd", is not compared. + let c = synthetic(vec![entry("Zz Abc群", "a.one")]); + assert!(ranked(&c, "abcd").is_empty()); + // The whole query is read with the word it is a typo of: "gruop" names Group as "group" does. + let c = synthetic(vec![entry("Group Selection Tool", "tool:groupSelection"), entry("Object › Group", "object.group")]); + assert_eq!(ranked(&c, "gruop"), ranked(&c, "group")); + assert_eq!(ranked(&c, "gruop").first().map(String::as_str), Some("object.group")); + // The rest of the query is read as typed, `›` included. + let c = synthetic(vec![entry("Object › Group Zz Tool", "tool:zz"), entry("Object › Group", "object.group")]); + assert_eq!(ranked(&c, "object › group"), ["object.group", "tool:zz"]); + assert_eq!(ranked(&c, "object › gruop"), ranked(&c, "object › group")); + // A label typo is read with the word of the label, even when a word of the menu path is + // nearer: "abcdefgh" reads as "abcdefyy" in the first, which is then its label. + let c = synthetic(vec![entry("Abcdefyy Zz", "tool:b"), entry("Abcdefgx › Abcdefyy", "a.one")]); + assert_eq!(ranked(&c, "abcdefgh"), ["a.one", "tool:b"]); + } + + /// A query word with a typo meets at most 32 words, the nearest first, and a long word with no + /// match finds nothing. + #[test] + fn a_typo_meets_at_most_32_words() { + // 35 words one edit from the query and one word two edits from it, which sorts before them. + let near = ('a'..='z').chain('0'..='9').filter(|&ch| ch != 'q'); + let mut entries: Vec = near.enumerate().map(|(i, ch)| entry(&format!("Abcdefg{ch}"), &format!("a.n{i}"))).collect(); + entries.insert(0, entry("Abcdeaxq", "far.one")); + let c = synthetic(entries); + let found = ranked(&c, "abcdefgq"); + assert_eq!(found.len(), 32, "{found:?}"); + assert!(!found.contains(&"far.one".to_string())); + let c = synthetic(vec![entry("Abcdeaxq", "far.one")]); + assert_eq!(ranked(&c, "abcdefgq"), ["far.one"], "two edits in a word of 8 letters"); + assert!(ranked(&c, &"q".repeat(30)).is_empty()); + } + + /// On the English results, misspelled words list first the commands the word spelled right + /// lists first by labels, menu paths and ids (a typo does not match descriptions), the tool among + /// the first four, and a word of 3 letters is not read as a typo. + #[test] + fn misspelled_words_find_the_command() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + assert_eq!(first("gruop"), "object.group"); + let plain = Index::build(&c.list, &[], &[], |_| None); + let id = |&i: &u32| c.list.get(i as usize).map(|e| e.id.clone()).unwrap_or_default(); + for (typo, word, tool) in [ + ("eyedroper", "eyedropper", "tool:eyedropper"), + ("rectange", "rectangle", "tool:rectangle"), + ("elipse", "ellipse", "tool:ellipse"), + ("gruop", "group", "tool:groupSelection"), + ] { + assert!(substring_rule(&c, typo).is_empty(), "{typo} matched nothing before"); + let top = |q: &str| ranked(&c, q).into_iter().take(4).collect::>(); + let spelled_right: Vec = rank(&c.list, &plain, word).iter().take(4).map(id).collect(); + assert_eq!(top(typo), spelled_right, "{typo}"); + assert!(place(&c, typo, tool).is_some_and(|p| p < 4), "{typo}: {:?}", ranked(&c, typo)); + } + assert_eq!(first("pen"), "tool:pen"); + assert!(place(&c, "pen", "file.open").is_some(), "Open… holds the text"); + } + + /// A query word finds a result whose label or menu path holds another word of its group of words + /// with the same meaning: below a result whose label holds the word itself, above one whose menu + /// path holds the word, and with a menu path word of the group last. A stem form of the query word + /// and of a result's word meet the group too; ids, word starts and words of no group do not. + #[test] + fn a_word_with_the_same_meaning_finds_the_result() { + let c = synthetic(vec![ + entry("Delete › Zz Path", "d.four"), + entry("Remove › Zz Other", "c.three"), + entry("Zz Delete", "a.one"), + entry("Zz Remove", "b.two"), + ]); + assert_eq!(ranked(&c, "remove"), ["b.two", "a.one", "c.three", "d.four"]); + assert!(ranked(&c, "remo zz").iter().all(|id| id != "a.one" && id != "d.four"), "a word start is not looked up"); + let c = synthetic(vec![entry("Zz Reflect…", "a.one"), entry("Zz Reflecting", "b.two"), entry("Zz One", "reflect.one")]); + assert_eq!(ranked(&c, "flipped zz"), ["a.one", "b.two"], "stem forms on both sides, and no id"); + let c = synthetic(vec![entry("Zz Unite", "a.one"), entry("Zz Merge", "b.two")]); + assert_eq!(ranked(&c, "merge"), ["b.two"], "merge is in no group"); + assert_eq!(ranked(&c, "combine"), ["a.one"]); + // Among results that match equally well, the whole query read with the word of the same + // meaning ("colour" as "color") puts the label Color first, but never above a label that + // holds the query word itself. + let c = synthetic(vec![entry("Zz Color", "tool:zz"), entry("Color", "panel:color"), entry("Zz Colour", "c.three")]); + assert_eq!(ranked(&c, "colour"), ["c.three", "panel:color", "tool:zz"]); + } + + /// A catalog row adds words in the UI language to a group, and a word that is not a single word + /// or that is a word of another group is left out. + #[test] + fn a_catalog_row_adds_words_to_a_group() { + let entries = || vec![entry("Zz Delete", "a.one")]; + let row = |key: &str| (key == "remove, delete, erase, clear").then(|| "Entfernen, ganz weg, text".to_string()); + let with = Catalog { list: entries(), index: Index::build(&entries(), &[], &[], row), ranked: std::sync::Mutex::new(None) }; + assert_eq!(ranked(&with, "entfernen"), ["a.one"]); + assert!(ranked(&with, "ganz weg").is_empty(), "two words are left out"); + assert!(ranked(&with, "text").is_empty(), "text stays in its own group"); + let without = synthetic(entries()); + assert!(ranked(&without, "entfernen").is_empty(), "only while the row's language is the UI language"); + } + + /// A description is the params text without the groups of its schema and result: one fixture + /// of each shape the params texts take. + #[test] + fn a_description_leaves_out_the_schema_and_the_result() { + for (params, expected) in [ + // A schema, prose and a result. + ("{a: 1, b?: bool (true)} make it so → {changed, ids}", "make it so"), + // A quoted brace inside a schema. + ("{sep: \"}\" or \"{\" (\"}\")} split the text", "split the text"), + // A schema only. + ("{radius: pt (10)}", ""), + // An empty schema, then prose with no arrow. + ("{} choose the Corner Tool", "choose the Corner Tool"), + // Prose after the result. + ("{from?: index} → {index}: moves the document", ": moves the document"), + // Nested braces and brackets. + ("{a: {b: 1}, c: [x, {y}]} trims the path", "trims the path"), + // Alternative schemas. + ("{id, dx} or {items: [{id}…], dx} move anchors", "or move anchors"), + // A result in brackets or parentheses, and a result written as words. + ("{} → [name…] for the active document", "for the active document"), + ("{id} → ({x, y}) its place", "its place"), + ("{id} → its id.", "→ its id."), + // A group inside parentheses is text, and so is a group that is never closed. + ("fits it (as {x} does) here", "fits it (as {x} does) here"), + ("{a: 1 never closed", "{a: 1 never closed"), + // No group at all. + ("plain words\n here", "plain words here"), + ("", ""), + ] { + assert_eq!(description(params), expected, "{params}"); + } + // A long description ends at the end of a word. + let cut = description(&"word ".repeat(100)); + assert!(cut.chars().count() <= DESCRIPTION_CHARS && cut.ends_with(" word"), "{cut}"); + let cut = description(&format!("{}handles", "abcd ".repeat(59))); + assert!(cut.chars().count() <= DESCRIPTION_CHARS && cut.ends_with(" abcd"), "{cut}"); + let whole = format!("{}handles", "abcd ".repeat(58)); + assert_eq!(description(&whole), whole); + assert!(description_words("the and ids true false null of a 16 10pt x").eq(["10pt"])); + assert!(description_words("image's 'quoted' png").eq(["image's", "quoted", "png"])); + } + + /// A word of a description finds the result as a whole word, a stem form, a word start or a word + /// with the same meaning, below a result that holds the word in its label or menu path or inside + /// a word. A schema's words, words left out of descriptions and typos do not find it. + #[test] + fn a_word_of_the_description_finds_the_result() { + let c = described( + vec![ + entry("Zz Alpha", "a.one"), + entry("Zz Background", "b.two"), + entry("Zz Underbackground", "c.three"), + entry("Background › Zz Delta", "d.four"), + ], + &["{corners?: bool (true)} make the background of the images transparent → {changed}", "", "", ""], + ); + assert_eq!(ranked(&c, "transparent"), ["a.one"]); + assert_eq!(ranked(&c, "making images"), ["a.one"], "stem forms"); + assert_eq!(ranked(&c, "transp"), ["a.one"], "a word start"); + assert_eq!(ranked(&c, "background"), ["b.two", "d.four", "c.three", "a.one"]); + assert_eq!(ranked(&c, "bg"), ["b.two", "d.four", "a.one"], "a word with the same meaning"); + assert_eq!(ranked(&c, "transparent background"), ["a.one"]); + assert!(ranked(&c, "corners").is_empty(), "a word of the schema"); + assert!(ranked(&c, "changed").is_empty(), "a word of the result"); + assert!(ranked(&c, "the").is_empty(), "a word left out"); + assert!(ranked(&c, "trasnparent").is_empty(), "a typo"); + assert!(synthetic(vec![entry("Zz Alpha", "a.one")]).index.find("transparent").is_none()); + } + + /// A result found only by its description ranks below a result found through a typo of a word + /// of its label: "centr" starts "centred" in a description and is a typo of "center". A result + /// matched both ways ranks as matched through the typo. + #[test] + fn a_description_match_ranks_below_a_typo() { + let c = described(vec![entry("Zz Beta", "b.two"), entry("Zz Center", "a.one")], &["{} keeps the art centred on the page", ""]); + assert_eq!(ranked(&c, "centr"), ["a.one", "b.two"]); + assert_eq!(ranked(&c, "zz centr"), ["a.one", "b.two"]); + let both = described(vec![entry("Zz Center", "a.one"), entry("Center", "c.three")], &["", "{} keeps the art centred on the page"]); + assert_eq!(ranked(&both, "centr"), ["c.three", "a.one"]); + } + + /// On the English results, words of what a command does find it: "transparent background" + /// lists Remove Background… near the top, and "png" lists it below every result with png in its + /// name or menu path, while a word of its schema alone ("corners") does not list it. + #[test] + fn words_of_a_description_find_the_command() { + let c = catalog(Lang::EN, false); + let remove = "addon.image.removeBackground"; + let text = super::super::params_texts(&c.list); + let at = c.list.iter().position(|e| e.id == remove).unwrap(); + assert!(description(text[at]).starts_with("make the background of each image transparent"), "{}", description(text[at])); + assert!(substring_rule(&c, "transparent background").len() < ranked(&c, "transparent background").len()); + assert!(place(&c, "transparent background", remove).is_some_and(|p| p < 3), "{:?}", ranked(&c, "transparent background")); + let png = ranked(&c, "png"); + let below = png.iter().position(|id| id == remove).unwrap(); + let named = |e: &Entry| names(e).chain(e.home.as_deref()).any(|n| n.to_lowercase().contains("png")); + let with_png: Vec = c.list.iter().filter(|e| named(e)).filter_map(|e| png.iter().position(|id| *id == e.id)).collect(); + assert!(!with_png.is_empty() && with_png.iter().all(|&p| p < below), "{png:?}"); + assert!(place(&c, "corners", remove).is_none()); + assert!(place(&c, "corners", "effect:stylize.roundCorners").is_some_and(|p| p < 3), "{:?}", ranked(&c, "corners")); + } + + /// On the English results, everyday words find commands whose names use another word, and a + /// result whose label holds a word with the same meaning as the query ranks above one that holds + /// the query only in its menu path. + #[test] + fn words_with_the_same_meaning_find_the_command() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n); + for q in ["remove bg", "outline text", "flip", "combine", "vectorize", "colour"] { + assert!(substring_rule(&c, q).len() < ranked(&c, q).len(), "{q} finds more than before"); + } + assert_eq!(first("remove bg"), "addon.image.removeBackground"); + assert_eq!(first("outline text"), "type.createOutlines"); + assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); + assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); + assert!(ranked(&c, "vectorize").iter().take(3).any(|id| id.starts_with("imageTrace.")), "{:?}", ranked(&c, "vectorize")); + assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); + // A word that only starts other labels is in a group, and its labels follow the direct match. + assert_eq!(first("unite"), "object.pathfinder.unite"); + assert!(place(&c, "unite", "object.slice.combine").is_some(), "{:?}", ranked(&c, "unite")); + assert!(place(&c, "delete", "view.guides.clear").is_some(), "{:?}", ranked(&c, "delete")); + assert!(place(&c, "settings", "edit.preferences").is_some(), "{:?}", ranked(&c, "settings")); + let merge = ranked(&c, "merge"); + let unite = merge.iter().position(|id| id == "object.pathfinder.unite"); + let named = |id: &String| c.list.iter().any(|e| &e.id == id && split_name(&e.shown).0 == "Merge"); + assert!(merge.first().is_some_and(named), "{merge:?}"); + assert!(unite.is_none() || merge.iter().rposition(named) < unite, "{merge:?}"); + let (scale, vertical) = (place(&c, "type", "type.scaleTextAttributes"), place(&c, "type", "type.orientation.vertical")); + assert!(scale.is_some() && scale < vertical, "{scale:?} {vertical:?}"); + } + /// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there, /// under the same submenus. #[test] @@ -949,8 +1614,8 @@ mod tests { assert_eq!(of("tool:pen"), None); // The home's words find the result: Preferences… under the native bar's Settings. let native_catalog = catalog(Lang::EN, true); - assert!(place(&native_catalog, "settings pref", "edit.preferences").is_some()); - assert!(place(&c, "settings pref", "edit.preferences").is_none()); + assert!(place(&native_catalog, "vectorcraft settings pref", "edit.preferences").is_some()); + assert!(place(&c, "vectorcraft settings pref", "edit.preferences").is_none()); // The menu item's own label finds the result too: File › Exit runs Quit VectorCraft. assert!(place(&c, "exit", "app.quit").is_some()); } @@ -972,10 +1637,32 @@ mod tests { let c = catalog(Lang::EN, false); let built = started.elapsed(); let started = std::time::Instant::now(); - let index = Index::build(&c.list, &[]); + let params = super::super::params_texts(&c.list); + let index = Index::build(&c.list, &[], ¶ms, |_| None); println!("catalog {built:?}, index alone {:?}, {} results, {} bytes", started.elapsed(), c.list.len(), index.bytes()); + let started = std::time::Instant::now(); + let without = Index::build(&c.list, &[], &[], |_| None); + println!("index without descriptions {:?}, {} bytes", started.elapsed(), without.bytes()); let long = "q".repeat(200); - for q in ["e", "ea", "select", "bring front", "zzzz", long.as_str()] { + let typos = "gruop elipse rectange eyedroper trasnform patern gradeint symbl"; + let repeated = format!("{typos} ").repeat(3); + let queries = [ + "e", + "ea", + "select", + "bring front", + "zzzz", + "eyedroper", + "gruop zz", + "remove bg", + "colour", + "transparent background", + "png", + typos, + repeated.as_str(), + long.as_str(), + ]; + for q in queries { let started = std::time::Instant::now(); let runs = 100; for _ in 0..runs { diff --git a/crates/ui-egui/src/palette/words.rs b/crates/ui-egui/src/palette/words.rs new file mode 100644 index 0000000000..44176dbd24 --- /dev/null +++ b/crates/ui-egui/src/palette/words.rs @@ -0,0 +1,125 @@ +//! Words that mean the same thing when searching the command palette: VectorCraft's own groups, +//! written for this table. A query word in a group also finds results whose label or menu path +//! holds another word of its group ([`super::search`]). +//! +//! A word that is the whole label of a command stays out of a group whose other words name a +//! different command: Merge is the label of Pathfinder and Live Paint commands that are not Unite, +//! and Mirror is the label of a repeat that is not Reflect…, so these are in no group. Insert is left +//! out too, since it starts the labels of type commands that are not Place…. A word that only starts +//! or ends other labels can be in a group, and a search for another word of its group also lists +//! those labels: "unite" lists Combine Slices after Unite, and "delete" lists Clear Guides. Plural and +//! verb forms that the search's English stem forms already join (round and rounded) are not groups. +//! +//! A catalog may add a group's words in its language with a row in the `search` context: the group's +//! English words joined by ", ", then that language's words joined by ", ". The words join the group +//! while that language is the UI language. No catalog has to have these rows. The search splits +//! labels into words only at spaces and punctuation, so in a language written without spaces a row's +//! word finds only a label that is that word alone. + +/// The groups: lowercase single English words, at most `MAX_WORDS` in a group and `MAX_GROUPS` +/// groups, no word longer than [`MAX_CHARS`] characters and no word in two groups. +pub(crate) const GROUPS: &[&[&str]] = &[ + &["remove", "delete", "erase", "clear"], + &["background", "bg"], + &["image", "picture", "photo", "img", "bitmap"], + &["text", "type"], + &["reflect", "flip"], + &["unite", "combine"], + &["trace", "vectorize"], + &["color", "colour"], + &["gray", "grey"], + &["grayscale", "greyscale"], + &["center", "centre"], + &["duplicate", "clone"], + &["zoom", "magnify"], + &["rotate", "turn", "spin"], + &["scale", "resize"], + &["opacity", "transparency"], + &["font", "typeface"], + &["preferences", "settings", "prefs"], + &["artboard", "canvas"], + &["swatch", "palette"], + &["eyedropper", "dropper"], +]; + +/// The most groups [`GROUPS`] may hold. +#[cfg(test)] +const MAX_GROUPS: usize = 60; +/// The most words a group may hold. +#[cfg(test)] +const MAX_WORDS: usize = 6; +/// The most characters a word may have. +pub(crate) const MAX_CHARS: usize = 20; + +/// The context of a catalog row that adds a group's words in its language. +pub(crate) const CONTEXT: &str = "search"; + +/// The source text of group `group`'s row in a catalog: its words joined by ", ". +pub(crate) fn row_key(group: &[&str]) -> String { + group.join(", ") +} + +/// The words of a catalog row's translation `text`, each trimmed and lowercased with its runs of +/// whitespace made one space, and whether each is a single word of at most [`MAX_CHARS`] +/// characters that the search can look up. +pub(crate) fn row_words(text: &str) -> impl Iterator + '_ { + text.split(',').map(|w| { + let w = super::search::normalize(w); + let single = !w.is_empty() && w.chars().count() <= MAX_CHARS && super::search::is_one_word(&w); + (w, single) + }) +} + +/// What is wrong with a catalog's `search` row for `source` translated as `text`: a source that is +/// no group's [`row_key`], an empty word, a word that is not a single word, or a word that is a word +/// of another group. +#[cfg(test)] +pub(crate) fn row_problems(source: &str, text: &str) -> Vec { + let Some(group) = GROUPS.iter().position(|g| row_key(g) == source) else { + return vec![format!("{source:?} is not a group")]; + }; + let mut problems = vec![]; + for (w, single) in row_words(text) { + if w.is_empty() { + problems.push(format!("{source:?}: an empty word")); + } else if !single { + problems.push(format!("{source:?}: {w:?} is not a single word")); + } else if let Some(other) = GROUPS.iter().enumerate().find(|&(i, g)| i != group && g.contains(&w.as_str())) { + problems.push(format!("{source:?}: {w:?} is a word of {:?}", row_key(other.1))); + } + } + problems +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The table keeps to its limits: groups, words per group, characters per word, and each word + /// lowercase, a single word and in one group only. + #[test] + fn the_groups_keep_to_their_limits() { + assert!(GROUPS.len() <= MAX_GROUPS, "{} groups", GROUPS.len()); + let mut seen = std::collections::HashSet::new(); + for group in GROUPS { + assert!((2..=MAX_WORDS).contains(&group.len()), "{group:?}"); + for &w in *group { + assert!(w.chars().count() <= MAX_CHARS, "{w}"); + assert_eq!(super::super::search::normalize(w), w, "{w} is lowercase"); + assert!(super::super::search::is_one_word(w), "{w} is one word"); + assert!(seen.insert(w), "{w} is in two groups"); + } + } + } + + /// A catalog row passes when it names a group and adds single words of no other group, and fails + /// otherwise. + #[test] + fn catalog_rows_are_checked() { + assert!(row_problems("remove, delete, erase, clear", "entfernen, löschen").is_empty()); + assert_eq!(row_problems("remove, delete", "entfernen").len(), 1, "not a group's words"); + assert_eq!(row_problems("remove, delete, erase, clear", "entfernen,, löschen").len(), 1, "an empty word"); + assert_eq!(row_problems("remove, delete, erase, clear", "ganz entfernen").len(), 1, "two words"); + assert_eq!(row_problems("remove, delete, erase, clear", "Text").len(), 1, "a word of another group once lowercased"); + } +} diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 02c448755a..86faed9e2d 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -45,6 +45,8 @@ pub(crate) const PANEL_MIN_WIDTH: f32 = 220.0; /// Docking state that lives for the session only. #[derive(Default)] pub(crate) struct Runtime { + /// Geometry commands waiting for the main window's desktop origin, by floating window id. + native_geometry: BTreeMap, /// Where the dock area floats panels, as it was last drawn. space: Option>, /// A panel a command showed: its floating window comes forward on the next frame. @@ -745,7 +747,7 @@ fn shared_command_with(app: &mut VectorcraftApp, id: &str, params: &Value, legac if let Some(fields) = params.as_object_mut() { fields.insert("command".into(), Value::String(id.to_owned())); } - let command: DockCommand = serde_json::from_value(params).map_err(|e| e.to_string())?; + let mut command: DockCommand = serde_json::from_value(params).map_err(|e| e.to_string())?; match &command { DockCommand::Workspace { name } => return app.run("window.workspace", json!({"name": name})), DockCommand::NewWorkspace { name } => return app.run("window.workspace.new", json!({"name": name})), @@ -788,6 +790,7 @@ fn shared_command_with(app: &mut VectorcraftApp, id: &str, params: &Value, legac } _ => false, }; + let native = if legacy.is_none() { native_float_geometry(app, &mut command, &txn.workspace.layout) } else { None }; let mut actions = match (&command, &legacy) { (DockCommand::Float { panel, group, .. } | DockCommand::Dock { panel, group, .. }, Some(legacy)) => { legacy.actions(&txn.workspace.layout, panel, *group)? @@ -817,7 +820,77 @@ fn shared_command_with(app: &mut VectorcraftApp, id: &str, params: &Value, legac for action in actions { closed.extend(txn.apply(action)?); } - Ok(txn.commit(app, closed, reveal)) + if let Some(NativeFloatGeometry::Ready { panel, rect, .. }) = &native { + closed.extend(txn.apply(Action::SetNative { panel: panel.clone(), rect: Some(*rect) })?); + } + let result = txn.commit(app, closed, reveal); + match native { + Some(NativeFloatGeometry::Deferred { window, params }) => { + let layout = layout_of(&app.ui); + app.dock_rt + .native_geometry + .retain(|id, (generation, _)| *generation == app.ui.docking_generation && layout.floating.iter().any(|window| window.id == *id)); + app.dock_rt.native_geometry.insert(window, (app.ui.docking_generation, params)); + } + Some(NativeFloatGeometry::Ready { window, .. }) => { + app.dock_rt.native_geometry.remove(&window); + } + None => {} + } + Ok(result) +} + +enum NativeFloatGeometry { + Ready { window: u64, panel: String, rect: [f32; 4] }, + Deferred { window: u64, params: Value }, +} + +fn native_float_geometry(app: &VectorcraftApp, command: &mut DockCommand, layout: &Layout) -> Option { + let DockCommand::Float { panel, x, y, width, height, group, column } = command else { return None }; + if [*x, *y, *width, *height].iter().all(Option::is_none) { + return None; + } + let window = floating_window(layout, panel)?; + let whole = *column || window.panels().count() == 1 || (*group && matches!(window.root, Node::Tabs { .. } | Node::Stack { .. })); + if !whole { + return None; + } + let [old_x, old_y, old_width, old_height] = window.native?; + if let Some((_, params)) = app.dock_rt.native_geometry.get(&window.id).filter(|(generation, _)| *generation == app.ui.docking_generation) { + let previous = |name| params.get(name).and_then(Value::as_f64).map(|value| value as f32); + *x = x.or_else(|| previous("x")); + *y = y.or_else(|| previous("y")); + *width = width.or_else(|| previous("width")); + *height = height.or_else(|| previous("height")); + } + let origin = app + .ui_ctx + .as_ref() + .and_then(|ctx| ctx.input(|input| input.raw.viewports.get(&egui::ViewportId::ROOT).and_then(|v| v.inner_rect))) + .map(|rect| rect.min) + .filter(|origin| origin.is_finite()); + let Some(origin) = origin else { + let mut params = app + .dock_rt + .native_geometry + .get(&window.id) + .filter(|(generation, _)| *generation == app.ui.docking_generation) + .map_or_else(|| json!({}), |(_, params)| params.clone()); + let fields = params.as_object_mut()?; + fields.insert("panel".into(), json!(panel)); + fields.insert("group".into(), json!(group)); + fields.insert("column".into(), json!(column)); + for (name, value) in [("x", *x), ("y", *y), ("width", *width), ("height", *height)] { + if let Some(value) = value { + fields.insert(name.into(), json!(value)); + } + } + return Some(NativeFloatGeometry::Deferred { window: window.id, params }); + }; + // Native windows report desktop coordinates; float commands use the main window's points. + let rect = + [*x.get_or_insert(old_x - origin.x), *y.get_or_insert(old_y - origin.y), *width.get_or_insert(old_width), *height.get_or_insert(old_height)]; + Some(NativeFloatGeometry::Ready { window: window.id, panel: panel.clone(), rect: [origin.x + rect[0], origin.y + rect[1], rect[2], rect[3]] }) } /// One action from the renderer: the user's own gesture. @@ -1128,6 +1201,23 @@ fn known(action: &Action) -> bool { pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let area = area_id(); let ctx = ui.ctx().clone(); + let origin = ctx.input(|input| input.raw.viewports.get(&egui::ViewportId::ROOT).and_then(|v| v.inner_rect)).map(|rect| rect.min); + if origin.is_some_and(|origin| origin.is_finite()) { + for (window, (generation, mut params)) in std::mem::take(&mut app.dock_rt.native_geometry) { + if generation != app.ui.docking_generation { + continue; + } + let layout = layout_of(&app.ui); + let panel = layout.floating.iter().find(|floating| floating.id == window).and_then(|floating| floating.panels().next()).cloned(); + let (Some(panel), Some(fields)) = (panel, params.as_object_mut()) else { continue }; + // The original panel may have docked while other panels kept this native window. + fields.insert("panel".into(), json!(panel)); + fields.insert("column".into(), json!(true)); + if let Err(error) = shared_command(app, "window.panel.float", ¶ms) { + app.ui.status = error; + } + } + } crate::tools_float::set_dock_area_left(&ctx, ui.available_rect_before_wrap().left()); let changed_workspace = ctx.data_mut(|data| { let previous = data.get_temp::(area.with("generation")); diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 23bce58d10..b20ceeb25f 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -306,6 +306,58 @@ impl egui::DroppedFile for MockDrop { } } +#[test] +fn an_explicit_float_command_updates_an_existing_native_windows_geometry() { + for mode in [json!({}), json!({"group": true}), json!({"column": true})] { + let mut h = Harness::new(); + h.app.run("window.panel.float", json!({"panel": "swatches", "x": 240, "y": 160, "width": 320, "height": 360})).unwrap(); + h.frames(3); + let viewport = h.viewport("swatches"); + assert_eq!(h.host.borrow().windows[&viewport].rect, Rect::from_min_size(ORIGIN + vec2(240.0, 160.0), vec2(320.0, 360.0))); + let mut params = json!({"panel": "swatches", "x": 280, "y": 190, "width": 350, "height": 390}); + params.as_object_mut().unwrap().extend(mode.as_object().unwrap().clone()); + h.app.run("window.panel.float", params).unwrap(); + h.frames(3); + assert_eq!(h.viewport("swatches"), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect, Rect::from_min_size(ORIGIN + vec2(280.0, 190.0), vec2(350.0, 390.0))); + let moved = Rect::from_min_size(pos2(-500.0, 120.0), vec2(380.0, 410.0)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().rect = moved; + h.frames(3); + let mut params = json!({"panel": "swatches", "width": 400}); + params.as_object_mut().unwrap().extend(mode.as_object().unwrap().clone()); + h.app.run("window.panel.float", params).unwrap(); + h.frames(3); + let resized = Rect::from_min_size(moved.min, vec2(400.0, moved.height())); + assert_eq!(h.host.borrow().windows[&viewport].rect, resized); + let mut params = json!({"panel": "swatches"}); + params.as_object_mut().unwrap().extend(mode.as_object().unwrap().clone()); + h.app.run("window.panel.float", params).unwrap(); + h.frames(3); + assert_eq!(h.host.borrow().windows[&viewport].rect, resized); + } +} + +#[test] +fn saved_native_geometry_updates_before_viewport_metadata_is_available() { + let mut h = Harness::new(); + let viewport = h.float("swatches"); + h.app.ui_ctx = None; + h.app.run("window.panel.float", json!({"panel": "swatches", "x": 280, "y": 190, "height": 390})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "swatches", "width": 350})).unwrap(); + h.frames(3); + assert_eq!(h.viewport("swatches"), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect, Rect::from_min_size(ORIGIN + vec2(280.0, 190.0), vec2(350.0, 390.0))); + h.app.run("window.panel.float", json!({"panel": "color", "onto": "swatches"})).unwrap(); + h.frames(3); + h.app.ui_ctx = None; + h.app.run("window.panel.float", json!({"panel": "swatches", "column": true, "x": 480, "y": 260})).unwrap(); + h.app.run("window.panel.dock", json!({"panel": "swatches", "anchor": "layers", "zone": "tab"})).unwrap(); + h.frames(3); + assert!(!floats(&h.app.ui, "swatches")); + assert_eq!(h.viewport("color"), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(480.0, 260.0)); +} + #[test] fn a_floated_panel_opens_its_own_os_window_where_the_backend_has_viewports() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2e1b81e732..9734f76867 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -38,6 +38,7 @@ pub mod opentype; pub mod paragraph; pub mod pathfinder; pub mod pattern_options; +pub mod preflight; pub mod properties; pub mod script_console; pub mod separations; @@ -188,6 +189,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { "colorThemes" => color_themes::show(app, ui), color_wheel::ID => color_wheel::show(app, ui), links::ID => links::show(app, ui), + preflight::ID => preflight::show(app, ui), asset_export::ID => asset_export::show(app, ui), css_properties::ID => css_properties::show(app, ui), three_d::ID => three_d::show(app, ui), diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 365a878421..2696c78c08 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,7 +3,8 @@ //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from //! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it +//! double-click opens Graphic Style Options. Dragging a style moves it in the list (dropped on +//! another style with Alt held, replaces that style with its look), applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a //! copy of it and of the styles highlighted with it at the end of the list; art dragged off the //! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and @@ -368,6 +369,8 @@ struct Events { new_from: Option, /// Art or an appearance dropped on a style with Alt held: the style takes this object's look. replaced: Option<(String, NodeId)>, + /// A style dropped on another with Alt held: the second (`.0`) takes the first's (`.1`) look. + restyled: Option<(String, String)>, /// The style the right button is held on. large: Option, /// A style is dragged over a tile or row. @@ -387,7 +390,8 @@ fn clicked(ui: &Ui, resp: &Response, name: &str) -> Option { /// Clicks, drags and the right button on the tile or row `resp` of style `i` of `d` (`list`: rows /// stack downwards). A drag from it carries the style ([`PanelDrag::GraphicStyle`]); a style -/// dragged over it lands before or after it by the pointer's half. Art (its first object) or the +/// dragged over it lands before or after it by the pointer's half, or with Alt held outlines it +/// and, released there, replaces it with the dragged style's look. Art (its first object) or the /// Appearance panel's thumbnail held over it with Alt outlines it, and released there replaces the /// style with that object's look; without Alt it is left to the list ([`zone_input`]). fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: &mut Events) { @@ -414,6 +418,11 @@ fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: if moving == name { // Dropped on itself: it stays where it is. resp.dnd_release_payload::(); + } else if alt_held(ui) { + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::().is_some() { + ev.restyled = Some((name.clone(), moving.clone())); + } } else { let r = resp.rect; let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()); @@ -531,6 +540,9 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { { run(app, "graphicStyle.redefine", json!({ "name": name, "id": id.0 })); } + if let Some((name, from)) = ev.restyled { + run(app, "graphicStyle.redefine", json!({ "name": name, "from": from })); + } match ev.click { Some(Click::Pick(name, _)) if picker => { app.run("graphicStyle.apply", json!({"name": name, "add": alt_held(ui)})).ok(); @@ -1535,10 +1547,10 @@ mod tests { assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); app.run("edit.undo", json!({})).unwrap(); - // A style dragged onto Red with Alt moves and replaces nothing. + // A style dragged onto Red without Alt moves and replaces nothing. let last = n.last().unwrap().clone(); egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(last.clone())); - frame_at(&mut app, at, release(at, alt), alt); + frame_at(&mut app, at, release(at, none), none); assert_eq!(names(&app)[0], last, "{view:?}"); assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); app.run("edit.undo", json!({})).unwrap(); @@ -1557,6 +1569,91 @@ mod tests { } } + /// A style dropped on another with Alt held replaces that style's look with its own: the + /// replaced style keeps its name, place and id, and its art follows, in one undo step; the + /// dragged style and its art stay as they are. Without Alt the style moves; dropped on itself + /// it does nothing. + #[test] + fn a_style_dropped_on_another_with_alt_replaces_that_style() { + let mut app = app(); + let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id; + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap(); + app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + let oval = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Green", "id": oval.0})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events` and `modifiers` held: whether a drop-target outline + // the size of one style's tile or row is drawn around `at`. + let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec, modifiers: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0, + _ => false, + }) + }; + let release = |at: egui::Pos2, modifiers: egui::Modifiers| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + vec![egui::Event::PointerMoved(at), up] + }; + let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT); + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (red, green) = (doc(&app).graphic_style("Red").unwrap().clone(), doc(&app).graphic_style("Green").unwrap().clone()); + let (red_fill, green_fill) = (red.appearance.fill_paint(), green.appearance.fill_paint()); + assert_ne!(red_fill, green_fill); + // The first style: the top of the list's first row, or its first tile. + for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] { + app.ui.graphic_styles_view = view; + frame_at(&mut app, at, vec![], none); + let n = names(&app); + assert_eq!(n[0], "Red", "{view:?}"); + let before = steps(&app); + // Held over Red with Alt it is outlined; without Alt it is not (the insertion marker shows instead). + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?}: outlined with Alt"); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}: holding it there changes nothing"); + + // Released there with Alt: Red takes Green's look and keeps its name, place and id. + frame_at(&mut app, at, release(at, alt), alt); + let d = doc(&app); + assert_eq!(names(&app), n, "{view:?}: no style moves"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, &g.appearance), (red.id, &green.appearance), "{view:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green_fill, "{view:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + assert_eq!(d.graphic_style("Green").unwrap(), &green, "{view:?}: Green stays as it was"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(green.id), "{view:?}: the oval stays linked to Green"); + assert_eq!(steps(&app), before + 1, "{view:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap(), &red, "{view:?}: undo restores the style"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red_fill, "{view:?}"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + + // Red dropped on itself with Alt changes nothing and records nothing. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Red".into())); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + + // Without Alt, Green moves before Red and Red keeps its look. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app)[0], "Green", "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}"); + } + } + #[test] fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/learn/locate.rs b/crates/ui-egui/src/panels/learn/locate.rs index 607da1c45c..b678049c0e 100644 --- a/crates/ui-egui/src/panels/learn/locate.rs +++ b/crates/ui-egui/src/panels/learn/locate.rs @@ -103,8 +103,12 @@ pub(crate) fn mark(app: &mut VectorcraftApp, ctx: &Context, layer: LayerId, clip l.drawn = true; ctx.request_repaint_after_secs(left as f32); let t = Tokens::get(ctx); - let painter = ctx.layer_painter(layer).with_clip_rect(clip.intersect(ctx.content_rect())); - painter.rect_stroke(rect.shrink(1.0), CornerRadius::same(6), Stroke::new(MARK_WIDTH, t.selection), StrokeKind::Inside); + outline(&ctx.layer_painter(layer).with_clip_rect(clip.intersect(ctx.content_rect())), rect, t.selection); +} + +/// Outline `rect`, a control that a mark points at, with `painter` in `color`. +pub(crate) fn outline(painter: &egui::Painter, rect: Rect, color: egui::Color32) { + painter.rect_stroke(rect.shrink(1.0), CornerRadius::same(6), Stroke::new(MARK_WIDTH, color), StrokeKind::Inside); } /// After the toolbars and panels have drawn: Escape ends the locate, also an Escape that closed the @@ -161,46 +165,76 @@ pub(crate) fn locate_tool(app: &mut VectorcraftApp, p: &Value) -> Result return Err(format!("`{key}` must be a string")), }; let tool = vectorcraft_tools::tool_info(tool).ok_or_else(|| format!("unknown tool `{tool}`"))?.id; + let found = match find(app, tool, false) { + Ok(found) => found, + Err(reason) => return Ok(unavailable(tool, reason)), + }; + match found.target { + Target::Tools => { + app.ui.toolbar = true; + start(app, tool, Target::Tools); + Ok(json!({"tool": tool, "location": found.location, "toolbar": null})) + } + Target::Custom(name) => { + start(app, tool, Target::Custom(name.clone())); + Ok(json!({"tool": tool, "location": found.location, "toolbar": name})) + } + Target::AllTools => { + app.run("window.editToolbar", json!({"open": true}))?; + start(app, tool, Target::AllTools); + Ok(json!({"tool": tool, "location": "allTools", "toolbar": null})) + } + } +} + +/// Where a toolbar holds a tool: [`find`]'s answer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Found { + /// The control that shows the tool. + pub target: Target, + /// `toolbar` (its slot's button shows it), `flyout` (it is hidden in its slot's group), + /// `strip` (its group is torn off into a strip) or `allTools`. + pub location: &'static str, + /// The tool the slot's button shows, for `toolbar` and `flyout`. + pub shown: Option<&'static str>, +} + +/// Where `tool` is in the current layout, without showing or opening anything: the Tools panel's +/// toolbar first, also while Window › Tools hides it, then the shown toolbars made with New +/// Toolbar, else the All Tools drawer. With `shown_first`, a hidden Tools panel comes after the +/// toolbars made with New Toolbar. An error names why no toolbar can show the tool now. +pub(crate) fn find(app: &VectorcraftApp, tool: &'static str, shown_first: bool) -> Result { if app.ui.screen_mode >= 3 { - return Ok(unavailable(tool, "Presentation Mode hides the toolbars: change the screen mode to show them")); + return Err("Presentation Mode hides the toolbars: change the screen mode to show them"); } // Tab hides the toolbars made with New Toolbar until the next Tab, also once Window › Tools // shows the Tools panel again. let tab_hid = app.ui.tab_hid.is_some(); if tab_hid && !app.ui.toolbar { - return Ok(unavailable(tool, "Tab has hidden the toolbars: press Tab to show them")); + return Err("Tab has hidden the toolbars: press Tab to show them"); } - if let Some(slot) = crate::toolbar::slots(app).into_iter().map(|(_, s)| s).find(|s| s.contains(&tool)) { - let location = if slot.len() > 1 && crate::toolbar::is_floating(app, None, slot[0]) { - "strip" - } else if crate::toolbar::shown_tool(app, &slot) == tool { - "toolbar" + let main = crate::toolbar::slots(app).into_iter().map(|(_, s)| s).find(|s| s.contains(&tool)).map(|slot| { + if slot.len() > 1 && crate::toolbar::is_floating(app, None, slot[0]) { + Found { target: Target::Tools, location: "strip", shown: None } } else { - "flyout" - }; - app.ui.toolbar = true; - start(app, tool, Target::Tools); - return Ok(json!({"tool": tool, "location": location, "toolbar": null})); + let shown = crate::toolbar::shown_tool(app, &slot); + Found { target: Target::Tools, location: if shown == tool { "toolbar" } else { "flyout" }, shown: Some(shown) } + } + }); + if let Some(main) = main.clone().filter(|_| !shown_first || app.ui.toolbar) { + return Ok(main); } let active = app.session.tool_id(); let custom = app.ui.custom_toolbars.iter().filter(|b| b.shown && !tab_hid).find_map(|bar| { let slot = bar.slots.iter().find(|s| s.iter().any(|t| t == tool))?; let tools: Vec<&'static str> = slot.iter().filter_map(|id| vectorcraft_tools::tool_info(id).map(|t| t.id)).collect(); let first = *tools.first()?; - let location = if tools.len() > 1 && crate::toolbar::is_floating(app, Some(&bar.name), first) { - "strip" - } else if crate::custom_toolbars::shown_tool(bar, active, &tools) == Some(tool) { - "toolbar" - } else { - "flyout" - }; - Some((bar.name.clone(), location)) + let target = Target::Custom(bar.name.clone()); + if tools.len() > 1 && crate::toolbar::is_floating(app, Some(&bar.name), first) { + return Some(Found { target, location: "strip", shown: None }); + } + let shown = crate::custom_toolbars::shown_tool(bar, active, &tools); + Some(Found { target, location: if shown == Some(tool) { "toolbar" } else { "flyout" }, shown }) }); - if let Some((name, location)) = custom { - start(app, tool, Target::Custom(name.clone())); - return Ok(json!({"tool": tool, "location": location, "toolbar": name})); - } - app.run("window.editToolbar", json!({"open": true}))?; - start(app, tool, Target::AllTools); - Ok(json!({"tool": tool, "location": "allTools", "toolbar": null})) + Ok(custom.or(main).unwrap_or(Found { target: Target::AllTools, location: "allTools", shown: None })) } diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs new file mode 100644 index 0000000000..0be4c4296b --- /dev/null +++ b/crates/ui-egui/src/panels/preflight.rs @@ -0,0 +1,224 @@ +//! Window › Production Preflight. Results follow the active document/revision and chosen output; +//! file and font changes outside the document are rechecked periodically while the panel is open. + +use egui::Ui; +use serde_json::{Value, json}; + +use super::{empty_state, pstate, set_pstate}; +use crate::VectorcraftApp; +use crate::theme::Tokens; +use crate::widgets::{self, dim_label}; + +pub const ID: &str = "preflight"; +const OPTIONS: &str = "production-preflight-options"; +const CACHE: &str = "production-preflight-cache"; +const RECHECK: f64 = 2.0; + +#[derive(Clone)] +struct Options { + output: usize, + active_only: bool, + min_ppi: f64, +} + +impl Default for Options { + fn default() -> Self { + Self { output: 0, active_only: false, min_ppi: 300.0 } + } +} + +#[derive(Clone, Default)] +struct Cache { + /// Document identity, revision, output, artboard scope and resolution threshold. + key: Option<(u64, u64, usize, Option, u64)>, + at: f64, + report: Value, + error: Option, +} + +fn cached(app: &mut VectorcraftApp, ui: &Ui, o: &Options, force: bool) -> Cache { + let Some(st) = app.session.active() else { return Cache::default() }; + let board = o.active_only.then(|| app.view().map_or(0, |v| v.artboard)); + let key = Some((st.uid, st.revision, o.output, board, o.min_ppi.to_bits())); + let now = ui.input(|i| i.time); + let mut c: Cache = pstate(ui.ctx(), CACHE); + if force || c.key != key || now - c.at >= RECHECK { + let output = ["pdf", "print", "screen"].get(o.output).copied().unwrap_or("pdf"); + let mut params = json!({ "output": output, "minPpi": o.min_ppi }); + if let Some(i) = board { + params["artboards"] = json!([i]); + } + match app.session.execute("document.preflight", ¶ms) { + Ok(v) => { + c.report = v; + c.error = None; + } + Err(e) => { + c.report = Value::Null; + c.error = Some(e.to_string()); + } + } + (c.key, c.at) = (key, now); + set_pstate(ui.ctx(), CACHE, c.clone()); + } + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(RECHECK)); + c +} + +fn kind_label(kind: &str) -> &str { + match kind { + "fonts" => tl!("Fonts"), + "text" => tl!("Text Overflow"), + "links" => tl!("Linked Files"), + _ => tl!("Image Resolution"), + } +} + +fn reason(code: &str) -> &str { + match code { + "missingFont" => tl!("Missing font; fallback will be used"), + "substitutedFont" => tl!("Missing font style; closest style will be used"), + "overflow" => tl!("Text past the frame will be left out"), + "missingLink" => tl!("Linked file is missing"), + "modifiedLink" => tl!("Linked file changed; update it before delivery"), + _ => tl!("Image resolution is below the minimum"), + } +} + +/// All locating actions go through commands. Resource findings name a visible canvas owner. +fn locate(app: &mut VectorcraftApp, finding: &Value) { + let ids = finding["ids"].as_array().cloned().unwrap_or_default(); + if ids.is_empty() { + return; + } + let selected = match app.run("select.set", json!({ "ids": ids })) { + Ok(result) => result, + Err(error) => { + app.ui.status = error; + return; + } + }; + // Selection can succeed while dropping artwork protected by a locked artboard. + let selected: std::collections::HashSet<_> = selected["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + let found = ids.iter().filter_map(Value::as_u64).filter(|id| selected.contains(id)).count(); + if found > 0 + && let Err(error) = app.run(crate::addons::arrange::ZOOM, json!({})) + { + app.ui.status = error; + return; + } + let warning = tl!("Some affected artwork could not be selected. Unlock it or its artboard, or leave isolation mode, then try again."); + if found < ids.len() { + app.ui.status = warning.to_string(); + } else if app.ui.status == warning { + app.ui.status.clear(); + } +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + if app.session.active().is_none() { + empty_state(ui, "dc-list-view", "Production Preflight", "Open a document to check it before delivery."); + return; + } + let mut options: Options = pstate(ui.ctx(), OPTIONS); + let labels = [tl!("PDF"), tl!("Print"), tl!("Screen")]; + widgets::label_row(ui, tl!("Output:"), 74.0, |ui| { + let shown = labels.get(options.output).copied().unwrap_or(labels[0]); + if let Some(i) = widgets::dropdown(ui, "preflight-output", shown, &labels, ui.available_width().max(90.0)) { + options.output = i; + options.min_ppi = if i == 2 { 96.0 } else { 300.0 }; + } + }); + widgets::label_row(ui, tl!("Minimum PPI:"), 90.0, |ui| { + if let Some(ppi) = widgets::range_field(ui, "preflight-ppi", options.min_ppi, 1.0..=9600.0, "", 0, 80.0) { + options.min_ppi = ppi; + } + }); + ui.checkbox(&mut options.active_only, tl!("Active Artboard Only")); + let force = ui.button(tl!("Recheck")).clicked(); + set_pstate(ui.ctx(), OPTIONS, options.clone()); + ui.separator(); + if app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy() { + dim_label(ui, tl!("Preflight updates when the edit finishes.")); + return; + } + let cache = cached(app, ui, &options, force); + if let Some(error) = cache.error { + ui.colored_label(Tokens::get(ui.ctx()).error, tl!("Preflight could not complete")); + ui.label(crate::i18n::msg(&error)); + return; + } + let report = &cache.report; + let height = ui.available_height().clamp(100.0, 600.0); + widgets::panel_scroll(ui, egui::ScrollArea::vertical().id_salt("preflight-findings").max_height(height).auto_shrink([false, true]), |ui| { + results(app, ui, report); + }); +} + +fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { + let findings = report["findings"].as_array().map_or(&[][..], Vec::as_slice); + let tokens = Tokens::get(ui.ctx()); + for check in report["checks"].as_array().into_iter().flatten() { + let kind = check["kind"].as_str().unwrap_or_default(); + let count = check["count"].as_u64().unwrap_or(0); + let (status, color) = match check["status"].as_str() { + Some("passed") => (tl!("Passed"), tokens.text), + Some("failed") => (tl!("Needs attention"), tokens.warning), + _ => (tl!("Not checked"), tokens.text_dim), + }; + ui.horizontal_wrapped(|ui| { + ui.strong(kind_label(kind)); + ui.colored_label(color, status); + if count > 0 { + ui.label(count.to_string()); + } + }); + for (index, finding) in findings.iter().enumerate().filter(|(_, f)| f["kind"] == kind) { + let name = finding["name"].as_str().unwrap_or_default(); + let code = finding["code"].as_str().unwrap_or_default(); + let text = format!("{name}\n{}", reason(code)); + ui.push_id(index, |ui| { + if ui + .add(egui::Button::new(text).wrap().min_size(egui::vec2(ui.available_width(), 0.0))) + .on_hover_text(tl!("Select and zoom to affected artwork")) + .clicked() + { + locate(app, finding); + } + if let Some(ppi) = finding["effectivePpi"].as_array() { + let values = ppi.iter().filter_map(Value::as_f64).map(|n| format!("{n:.0}")).collect::>(); + dim_label(ui, &format!("{}: {} ppi", tl!("Effective PPI"), values.join(" × "))); + } + let source = finding["sourceId"].as_u64(); + if code == "missingLink" + && ui.small_button(tl!("Relink…")).clicked() + && let Some(id) = source + { + app.run("ui.relinkDialog", json!({"ids": [id]})).ok(); + } + if code == "modifiedLink" + && ui.small_button(tl!("Update Link")).clicked() + && let Some(id) = source + { + app.run("links.update", json!({"ids": [id]})).ok(); + } + }); + } + if kind == "fonts" && count > 0 && ui.small_button(tl!("Find Font…")).clicked() { + app.run("type.findFont", json!({})).ok(); + } + if check["notChecked"].as_u64().unwrap_or(0) > 0 { + dim_label(ui, tl!("Resolution inside resource art or placed documents is not checked.")); + } + ui.add_space(6.0); + } + for warning in report["outputWarnings"].as_array().into_iter().flatten().filter_map(Value::as_str) { + ui.colored_label(tokens.warning, crate::i18n::msg(warning)); + } + ui.separator(); + dim_label(ui, tl!("Checks update after edits. Linked files are rechecked every two seconds.")); + dim_label(ui, tl!("These checks do not certify an exported file.")); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/panels/preflight/tests.rs b/crates/ui-egui/src/panels/preflight/tests.rs new file mode 100644 index 0000000000..448a114bbf --- /dev/null +++ b/crates/ui-egui/src/panels/preflight/tests.rs @@ -0,0 +1,179 @@ +use super::*; +use crate::panels::tests_appearance::{frame_raw, text_rect}; +use vectorcraft_engine::Session; + +fn app() -> (VectorcraftApp, Value) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({ "width": 500, "height": 400 })).unwrap(); + let id = app.run("text.create", json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight UI Missing 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone(); + app.run("object.setProps", json!({ "ids": [id], "name": "Delivery headline" })).unwrap(); + (app, id) +} + +fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, time: f64, events: Vec) -> Vec<(String, egui::Rect)> { + frame_raw( + ctx, + app, + egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(360.0, 1000.0))), + events, + ..Default::default() + }, + show, + ) +} + +fn text(rows: &[(String, egui::Rect)]) -> String { + rows.iter().map(|(s, _)| s.as_str()).collect::>().join("\n") +} + +#[test] +fn preflight_panel_rechecks_edits_undo_and_document_switches() { + let (mut app, id) = app(); + let ctx = egui::Context::default(); + let first = text(&frame(&ctx, &mut app, 1.0, vec![])); + assert!(first.contains("Preflight UI Missing 917") && first.contains("Text past the frame"), "{first}"); + app.run("text.areaOptions", json!({ "ids": [id], "height": 150 })).unwrap(); + let fixed = text(&frame(&ctx, &mut app, 1.1, vec![])); + assert!(!fixed.contains("Text past the frame"), "revision rechecks before the timer: {fixed}"); + app.run("edit.undo", json!({})).unwrap(); + assert!(text(&frame(&ctx, &mut app, 1.2, vec![])).contains("Text past the frame")); + app.run("file.new", json!({ "width": 500, "height": 400 })).unwrap(); + let clean = text(&frame(&ctx, &mut app, 1.3, vec![])); + assert!(!clean.contains("Preflight UI Missing 917") && !clean.contains("Needs attention"), "{clean}"); +} + +#[test] +fn clicking_a_preflight_finding_selects_and_zooms_to_its_artwork() { + let (mut app, id) = app(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let ctx = egui::Context::default(); + let rows = frame(&ctx, &mut app, 1.0, vec![]); + let at = text_rect(&rows, "Delivery headline\nText past the frame will be left out").center(); + let event = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&ctx, &mut app, 1.1, vec![egui::Event::PointerMoved(at), event(true)]); + frame(&ctx, &mut app, 1.2, vec![event(false)]); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id.as_u64().unwrap())]); + assert!(app.view().unwrap().fitted); + assert!(app.view().unwrap().zoom > 1.0); +} + +#[test] +fn clicking_a_preflight_finding_on_a_locked_artboard_reports_the_problem() { + let (mut app, id) = app(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + app.run("artboard.setProps", json!({ "index": 0, "locked": true })).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let before_view = *app.view().unwrap(); + let before_doc = app.session.active().unwrap().doc.clone(); + app.ui.status.clear(); + let ctx = egui::Context::default(); + let rows = frame(&ctx, &mut app, 1.0, vec![]); + let at = text_rect(&rows, "Delivery headline\nText past the frame will be left out").center(); + let event = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&ctx, &mut app, 1.1, vec![egui::Event::PointerMoved(at), event(true)]); + frame(&ctx, &mut app, 1.2, vec![event(false)]); + assert!(app.ui.status.contains("could not be selected"), "{}", app.ui.status); + assert!(app.session.active().unwrap().selection.objects.is_empty()); + assert_eq!(app.view().unwrap().zoom, before_view.zoom); + assert_eq!(*app.session.active().unwrap().doc, *before_doc); + app.run("artboard.setProps", json!({ "index": 0, "locked": false })).unwrap(); + locate(&mut app, &json!({ "ids": [id] })); + assert!(app.ui.status.is_empty(), "successful navigation clears its previous warning: {}", app.ui.status); + assert!(app.view().unwrap().fitted); +} + +#[test] +fn preflight_navigation_reports_partial_selection_and_zooms_to_selectable_artwork() { + let (mut app, locked) = app(); + app.run("artboard.new", json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap(); + let free = app.run("text.create", json!({ "x": 610, "y": 30, "text": "Free", "font": "Preflight UI Missing 917" })).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + app.run("artboard.setProps", json!({ "index": 0, "locked": true })).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let report = app.session.execute("document.preflight", &json!({})).unwrap(); + let finding = report["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap(); + assert!(finding["ids"].as_array().unwrap().contains(&locked)); + locate(&mut app, finding); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(free.as_u64().unwrap())]); + assert!(app.view().unwrap().fitted); + assert!(app.view().unwrap().zoom > 1.0); + assert!(app.ui.status.contains("could not be selected"), "{}", app.ui.status); +} + +#[test] +fn preflight_panel_does_not_present_stale_results_during_a_drag() { + let (mut app, _) = app(); + let ctx = egui::Context::default(); + frame(&ctx, &mut app, 1.0, vec![]); + app.session.begin_interaction("Preflight test").unwrap(); + let shown = text(&frame(&ctx, &mut app, 1.1, vec![])); + assert!(shown.contains("Preflight updates when the edit finishes."), "{shown}"); + assert!(!shown.contains("Passed") && !shown.contains("Needs attention"), "{shown}"); + app.session.cancel_interaction().unwrap(); +} + +#[test] +fn preflight_window_menu_and_empty_state_are_available() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("window.panel", json!({ "panel": ID })).unwrap(); + let ctx = egui::Context::default(); + let shown = text(&frame(&ctx, &mut app, 1.0, vec![])); + assert!(shown.contains("Open a document to check it before delivery."), "{shown}"); + assert!(crate::state::all_panels().any(|(id, name)| id == ID && name == "Production Preflight")); +} + +#[test] +fn preflight_panel_rechecks_missing_files_on_its_timer_and_on_request() { + let dir = vectorcraft_testkit::temp_dir("ui-preflight-timer"); + let path = dir.join("picture.png"); + let image = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![255; 16]) + .unwrap(); + let bytes = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(&path, &bytes).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({ "width": 500, "height": 400 })).unwrap(); + app.run("file.place", json!({ "path": path.to_string_lossy(), "at": [100, 100] })).unwrap(); + let ctx = egui::Context::default(); + frame(&ctx, &mut app, 1.0, vec![]); + let rev = app.session.active().unwrap().revision; + std::fs::remove_file(&path).unwrap(); + assert!(!text(&frame(&ctx, &mut app, 1.1, vec![])).contains("Linked file is missing")); + assert!(text(&frame(&ctx, &mut app, 3.1, vec![])).contains("Linked file is missing")); + assert_eq!(rev, app.session.active().unwrap().revision); + std::fs::write(&path, &bytes).unwrap(); + let rows = frame(&ctx, &mut app, 3.2, vec![]); + let at = text_rect(&rows, "Recheck").center(); + let event = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&ctx, &mut app, 3.3, vec![egui::Event::PointerMoved(at), event(true)]); + let after = text(&frame(&ctx, &mut app, 3.4, vec![event(false)])); + assert!(!after.contains("Linked file is missing"), "{after}"); + std::fs::remove_file(&path).unwrap(); +} + +/// An optional visual QA artifact, never a checked-in snapshot or an asset shipped by the app. +#[test] +#[ignore = "set PREFLIGHT_PREVIEW_PATH to write an offscreen GPU render for visual review"] +fn preflight_panel_preview() { + let (app, _) = app(); + let mut harness = egui_kittest::Harness::builder() + .with_size(egui::vec2(340.0, 480.0)) + .with_accessibility_check(false) + .with_context_setup(|ctx| { + crate::theme::install_fonts(ctx); + crate::theme::apply(ctx, crate::theme::Brightness::Dark); + }) + .build_ui_state( + |ui, app| { + ui.heading("Production Preflight"); + ui.separator(); + show(app, ui); + }, + app, + ); + harness.run_steps(3); + let path = std::env::var("PREFLIGHT_PREVIEW_PATH").expect("PREFLIGHT_PREVIEW_PATH"); + harness.render().unwrap().save(path).unwrap(); +} diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index f8dc10ac66..33faeec41e 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -416,7 +416,7 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - /// Draw an arrowhead preview (the head as the canvas draws it) in `r`: a line with the head at the /// left (`start`) or right end. -fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { +pub(crate) fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { if let Some(tex) = widgets::doc_preview(ui, &format!("arrow:{}:{start}", arrow_key(a)), r.size(), |w, h| arrow_doc(a.cloned(), start, w, h)) { ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), color); } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 81f6986883..048260b45e 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -401,11 +401,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.min_rect() }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); - if !over_symbol - && let Some(ids) = widgets::art_drop(ui, &zone) - && let Err(e) = app.run("symbol.new", json!({ "ids": ids, "type": "dynamic" })) - { - app.status(e); + if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { + // Shift held at the release keeps the dropped art as ordinary art. + let mut p = json!({ "ids": ids, "type": "dynamic" }); + if modifiers_at_release(ui).shift { + p["keepArt"] = json!(true); + } + if let Err(e) = app.run("symbol.new", p) { + app.status(e); + } } // Redefine Symbol with the dropped art, which becomes an instance of it, in one undo step. if let Some((name, ids)) = redefine @@ -437,6 +441,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button_enabled(ui, "link-2-off", tl!("Break Link to Symbol"), false, inst, 24.0).clicked() { app.run("symbol.breakLink", json!({})).ok(); } + // Opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does; + // Alt does the same. + if widgets::icon_button_enabled(ui, "dc-options", tl!("Symbol Options"), false, sel.is_some(), 24.0).clicked() { + app.run("ui.symbolOptions", json!({"edit": true, "name": sel})).ok(); + } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0); // A symbol dragged from the panel and dropped on New Symbol is duplicated, with or without @@ -447,8 +456,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } else if new.clicked() { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the - // dialog's default. - let (cmd, p) = if ui.input(|i| i.modifiers.alt) { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. + // Both are read as the primary button went up, when it did in this frame. + let m = modifiers_at_release(ui); + let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + if m.shift { + p["keepArt"] = json!(true); + } app.run(cmd, p).ok(); } // Alt deletes an unused symbol without asking; a symbol with instances still asks. @@ -457,9 +471,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // it: the dragged symbol, or every symbol Select All Unused picked when it is one of them. if let Some(name) = symbol_dropped(ui, &trash, &names, uid) { let picked = if marked.contains(&name) { &marked[..] } else { &[] }; - delete(app, picked, Some(&name), super::alt_held(ui)); + delete(app, picked, Some(&name), alt_at_release(ui)); } else if trash.clicked() { - delete(app, &marked, sel.as_deref(), super::alt_held(ui)); + delete(app, &marked, sel.as_deref(), alt_at_release(ui)); } }); } @@ -472,10 +486,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); - // Shift keeps the selected art as ordinary art instead of making it an instance. - let redefine = if ui.input(|i| i.modifiers.shift) { json!({"name": sel, "keepArt": true}) } else { name.clone() }; + // Shift keeps the selected art as ordinary art instead of making it an instance. It is read as + // the primary button went up, when it did in this frame. + let shift = modifiers_at_release(ui).shift; + let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() }; + let new = if shift { json!({"keepArt": true}) } else { json!({}) }; let items: [(&str, bool, &str, Value); 3] = [ - (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({})), + (tl!("New Symbol…"), has_sel, "ui.symbolOptions", new), (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine), (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), ]; @@ -579,17 +596,23 @@ fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option item.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) } -/// Whether Alt (Option) is held for a drop: when the primary button went up in this frame, as it +/// Whether Alt (Option) is held for a drop or a click: when the primary button went up in this frame, as it /// went up, else now. fn alt_at_release(ui: &Ui) -> bool { + modifiers_at_release(ui).alt +} + +/// The modifiers held for a drop or a click: when the primary button went up in this frame, as it went up, +/// else now. +fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { ui.input(|i| { i.events .iter() .find_map(|e| match e { - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(modifiers.alt), + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), _ => None, }) - .unwrap_or(i.modifiers.alt) + .unwrap_or(i.modifiers) }) } @@ -911,12 +934,20 @@ mod tests { /// Clicks the menu item labeled `label` with `modifiers` held. fn click_menu_held(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + click_menu_held_then(ctx, app, label, modifiers, vec![]); + } + + /// Clicks the menu item labeled `label` with `modifiers` held, `after` following the release in + /// its frame. + fn click_menu_held_then(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers, after: Vec) { let held = egui::Event::ModifiersChanged(modifiers); let labels = menu_frame(ctx, app, vec![held.clone()]); let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu")); let press = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers }; menu_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(item), press(true)]); - menu_frame(ctx, app, vec![held, press(false)]); + let mut last = vec![held, press(false)]; + last.extend(after); + menu_frame(ctx, app, last); } /// Redefine Symbol in the panel menu with Shift held updates the symbol and leaves the @@ -938,6 +969,205 @@ mod tests { assert_eq!(art(&app, "Dot"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// `leaf_and_dot` with a selected 60 × 20 rectangle; returns its id. + fn leaf_dot_and_rect() -> (VectorcraftApp, NodeId) { + let mut app = leaf_and_dot(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + (app, rect) + } + + /// New Symbol… in the panel menu with Shift held opens Symbol Options, and its OK makes the + /// symbol and leaves the selected art as ordinary art, still selected, in one undo step, though + /// Shift is let go before OK; Cancel makes no symbol. Without Shift, OK makes the art an + /// instance. + #[test] + fn shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + crate::dialogs::cancel(&mut app); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "Cancel makes no symbol"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + menu_frame(&ctx, &mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let undo = undo_len(&app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::NONE); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// Clicks the panel's New Symbol button with `modifiers` held. + fn click_new(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { + click_button_then(app, "New Symbol", modifiers, vec![]); + } + + /// Clicks the panel's button labeled `label` with `modifiers` held, `after` following the + /// release in its frame. + fn click_button_then(app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers, after: Vec) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + let mut events = vec![egui::Event::PointerMoved(at), press(true), press(false)]; + events.extend(after); + frame_held(&ctx, app, events, modifiers); + } + + /// Shift held as the primary button goes up on New Symbol, on the panel's button or in its + /// menu, or on Redefine Symbol in the menu, keeps the selected art as ordinary art, though Shift + /// is let go later in the same frame. Alt held as the button goes up on Delete Symbol deletes + /// an unused symbol without asking, in the same case. + #[test] + fn shift_or_alt_let_go_after_the_release_in_the_same_frame_still_counts() { + let let_go = || vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + let menu_ctx = || { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + }; + let (mut app, _) = leaf_dot_and_rect(); + click_button_then(&mut app, "New Symbol", egui::Modifiers::SHIFT, let_go()); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "New Symbol button with Shift: the rectangle stays ordinary art"); + let (mut app, _) = leaf_dot_and_rect(); + click_button_then(&mut app, "New Symbol", egui::Modifiers::SHIFT | egui::Modifiers::ALT, let_go()); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(art(&app, "New Symbol"), (0, 1), "New Symbol button with Shift and Alt: the rectangle stays ordinary art"); + let (mut app, _) = leaf_dot_and_rect(); + click_menu_held_then(&menu_ctx(), &mut app, "New Symbol…", egui::Modifiers::SHIFT, let_go()); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "New Symbol… with Shift: the rectangle stays ordinary art"); + let (mut app, _) = leaf_dot_and_rect(); + click_menu_held_then(&menu_ctx(), &mut app, "Redefine Symbol", egui::Modifiers::SHIFT, let_go()); + assert_eq!(art(&app, "Dot"), (0, 1), "Redefine Symbol with Shift: the rectangle stays ordinary art"); + let mut app = leaf_and_dot(); + click_button_then(&mut app, "Delete Symbol", egui::Modifiers::ALT, let_go()); + assert!(app.ui.dialog.is_none(), "Alt deletes an unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf"]); + } + + /// The New Symbol button with Shift held opens Symbol Options, whose OK keeps the selected art + /// as ordinary art; with Shift and Alt it makes the symbol at once under the default name and + /// keeps the art. Alt alone still makes the art an instance at once. + #[test] + fn shift_new_symbol_button_keeps_the_art_with_or_without_alt() { + let (mut app, rect) = leaf_dot_and_rect(); + click_new(&mut app, egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + assert_eq!(symbols(&mut app).len(), 2, "no symbol before OK"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + let undo = undo_len(&app); + click_new(&mut app, egui::Modifiers::SHIFT | egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol", "New Symbol 2"]); + assert_eq!(art(&app, "New Symbol 2"), (0, 1), "Shift and Alt: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_new(&mut app, egui::Modifiers::ALT); + assert_eq!(art(&app, "New Symbol 3"), (1, 0), "Alt alone: the rectangle becomes an instance"); + } + + /// The center of the panel's Symbol Options button, and of Break Link to Symbol and New Symbol + /// beside it, in a frame of `app`. + fn options_button(app: &mut VectorcraftApp) -> (Pos2, Pos2, Pos2) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let found = clickable(&frame_held(&ctx, app, vec![], egui::Modifiers::NONE)); + let at = |label: &str| found.iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + (at("Break Link to Symbol"), at("Symbol Options"), at("New Symbol")) + } + + /// Clicks the panel at `at` with `modifiers` held. + fn click_at(app: &mut VectorcraftApp, at: Pos2, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + frame_held(&ctx, app, vec![], modifiers); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// The bottom bar's Symbol Options button sits between Break Link to Symbol and New Symbol and + /// opens Symbol Options on the current symbol, as the panel menu's item does, with or without + /// Alt, and adds no undo step; in a document without symbols it is disabled and opens nothing. + #[test] + fn symbol_options_button_edits_the_current_symbol() { + let mut app = leaf_and_dot(); + app.run("select.all", json!({})).unwrap(); + let (break_link, options, new) = options_button(&mut app); + assert!(break_link.x < options.x && options.x < new.x, "Break Link, Symbol Options, New Symbol: {break_link:?} {options:?} {new:?}"); + let undo = undo_len(&app); + for (current, modifiers) in [("Dot", egui::Modifiers::NONE), ("Leaf", egui::Modifiers::ALT)] { + app.run("symbol.setCurrent", json!({ "name": current })).unwrap(); + click_at(&mut app, options, modifiers); + let d = app.ui.dialog.as_ref().expect("Symbol Options opens"); + assert_eq!(d.kind, crate::dialogs::symbol_options::KIND); + assert_eq!((d.fields.get("name"), d.fields.get("__edit")), (Some(&json!(current)), Some(&json!(true))), "{modifiers:?}"); + crate::dialogs::cancel(&mut app); + } + assert_eq!(undo_len(&app), undo, "opening the dialog adds no undo step"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + let mut empty = VectorcraftApp::new(Session::new(), Default::default()); + empty.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + for (app, disabled) in [(&mut app, false), (&mut empty, true)] { + let out = frame_held(&ctx, app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let button = &nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Symbol Options")).expect("a Symbol Options button").1; + assert_eq!(button.is_disabled(), disabled, "disabled without a current symbol"); + } + click_at(&mut empty, options, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&empty), None, "no symbol, no dialog"); + } + + /// Art dropped on the panel with Shift held as the primary button goes up becomes a new + /// symbol and stays ordinary art, still selected, though Shift is let go later in the same + /// frame; dropped without Shift, it becomes an instance. + #[test] + fn shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + let at = pos2(180.0, 60.0); + let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT); + let undo = undo_len(&app); + let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::SHIFT), let_go], egui::Modifiers::SHIFT); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::NONE)], egui::Modifiers::NONE); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. + #[test] + fn symbol_options_checks_keep_art() { + let (mut app, _) = leaf_dot_and_rect(); + for bad in [json!("yes"), json!(1)] { + let e = app.run("ui.symbolOptions", json!({ "keepArt": bad })).unwrap_err(); + assert!(e.contains("`keepArt` must be true or false"), "{bad}: {e}"); + } + let e = app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": true})).unwrap_err(); + assert!(e.contains("only to a new symbol"), "{e}"); + assert_eq!(dialog_kind(&app), None); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": false})).unwrap(); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + } + /// #4918: Select All Unused picks the symbols nothing places, Delete Symbol asks once and /// deletes them all in one undo step, and a click on a symbol picks one again. #[test] @@ -1667,12 +1897,7 @@ mod tests { /// Clicks the panel's Delete Symbol button with `modifiers` held. fn click_delete(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { - let ctx = egui::Context::default(); - ctx.enable_accesskit(); - let out = frame_held(&ctx, app, vec![], modifiers); - let at = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; - let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; - frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + click_button_then(app, "Delete Symbol", modifiers, vec![]); } /// Clicks the panel menu's Delete Symbol item. @@ -2303,7 +2528,8 @@ mod tests { frame(ctx, app, vec![egui::Event::PointerMoved(from + vec2(40.0, 40.0))]); frame(ctx, app, vec![egui::Event::PointerMoved(from + vec2(80.0, 80.0))]); let held = frame_held(ctx, app, vec![egui::Event::PointerMoved(to)], egui::Modifiers::NONE); - frame_held(ctx, app, vec![button(to, false)], modifiers); + let release = egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }; + frame_held(ctx, app, vec![release], modifiers); held } diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 87fe34953f..91fa8fa3b1 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -195,6 +195,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("art-ribbons"), json!("ink-and-wash"), json!("calligraphic-nibs"), + json!("pressure-sensitive"), json!("bristle-brushes"), json!("pattern-borders"), json!("scatter-shapes"), @@ -232,6 +233,17 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Pressure Sensitive"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4))); + let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 3.0); + assert!(has(&app, "Flex Ribbon") && !has(&app, "Pulse Stroke")); + assert_eq!(undo_len(&app), undo + 1); + assert_eq!( + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), + Some("Flex Ribbon") + ); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index b65161d131..d9fc0e0a2d 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -218,6 +218,9 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ), ("snapTangent", "Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve."), ("snapPerpendicular", "Snaps the end of a line segment so that it meets a nearby straight segment at a right angle."), + // Slices + ("showSliceNumbers", "Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show."), + ("sliceLineColor", "The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it."), ]; /// The sentence that describes the setting `key`, in English, or `None` when it has none yet. diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index be0450feac..cc7e452b30 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -20,6 +20,29 @@ fn marquee_selection_choices_are_saved_from_preferences() { assert!(text.contains("Drag Direction"), "{text}"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: shown with its choices, applied by OK, +/// saved with the UI state and read back from it when the app starts again. +#[test] +fn plugin_instruction_budget_shows_applies_and_restores() { + let mut a = app(); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Plug-in Instruction Budget") && text.contains("Normal"), "{text}"); + a.ui.dialog.as_mut().unwrap().fields.insert("pluginInstructionBudget".into(), json!("large")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["pluginInstructionBudget"], json!("large")); + let mut b = app(); + b.ui.engine_prefs = saved["engine_prefs"].clone(); + restore(&mut b); + assert_eq!(b.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + // A saved value this version doesn't offer reads as Normal, and the other preferences stay. + b.ui.engine_prefs = json!({"keyboardIncrement": 4, "pluginInstructionBudget": 7}); + restore(&mut b); + assert_eq!((b.session.prefs.plugin_instruction_budget, b.session.prefs.keyboard_increment), (vectorcraft_engine::PluginBudget::Normal, 4.0)); +} + #[test] fn geometric_snapping_is_a_saved_smart_guides_preference() { let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -1813,8 +1836,11 @@ fn a_row_without_a_description_leaves_the_line_empty() { description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(at(&texts, "General:"))]); let (texts, _) = description_frame(&mut a, &ctx, vec![]); assert!(painted(&texts, general), "the General row's sentence shows: {texts:?}"); - // Go to the Slices category and point at a row with no sentence. - let button = at(&texts, "Slices"); + // Go to the first other category that still has a row with no sentence (Slices when none is + // left) and point at that row. + let bare = settings().find(|s| s.category != "Units" && descriptions::description(s.key).is_none()); + let category = bare.map_or("Slices", |s| s.category); + let button = at(&texts, category); let press = |pressed| egui::Event::PointerButton { pos: button, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(button), press(true), press(false)]); let (texts, _) = description_frame(&mut a, &ctx, vec![]); @@ -1828,22 +1854,29 @@ fn a_row_without_a_description_leaves_the_line_empty() { description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(line.center())]); let (after, _) = description_frame(&mut a, &ctx, vec![]); empty(&after, "on the line after changing category"); - assert_eq!(descriptions::description("showSliceNumbers"), None); - description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(at(&texts, "Show Slice Numbers"))]); - let (after, _) = description_frame(&mut a, &ctx, vec![]); - empty(&after, "on Show Slice Numbers"); - description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(line.center())]); - let (after, _) = description_frame(&mut a, &ctx, vec![]); - empty(&after, "on the line after Show Slice Numbers"); + if bare.is_some() { + // A checkbox shows its label as it is; other rows show it with a colon. + let (label, pos) = settings() + .filter(|s| s.category == category && descriptions::description(s.key).is_none()) + .find_map(|s| texts.iter().find(|(t, _)| *t == s.label || *t == format!("{}:", s.label)).map(|(_, r)| (s.label, r.center()))) + .unwrap_or_else(|| panic!("no row of {category} without a sentence is drawn: {texts:?}")); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(pos)]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + empty(&after, &format!("on {label}")); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(line.center())]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + empty(&after, &format!("on the line after {label}")); + } assert_eq!(preferences_window(&ctx).size(), size); } -/// Every setting the General, Selection & Anchor Display, Guides & Grid and Smart Guides categories -/// show, the Smart Guides box included, has exactly one sentence, and no key has two. +/// Every setting the General, Selection & Anchor Display, Guides & Grid, Smart Guides and Slices +/// categories show, the Smart Guides box included, has exactly one sentence, and no key has two. #[test] -fn every_general_selection_guides_and_smart_guides_setting_has_one_description() { +fn every_general_selection_guides_smart_guides_and_slices_setting_has_one_description() { let mut bad = vec![]; - for s in settings().filter(|s| ["General", "Selection & Anchor Display", "Guides & Grid", "Smart Guides"].contains(&s.category)) { + let categories = ["General", "Selection & Anchor Display", "Guides & Grid", "Smart Guides", "Slices"]; + for s in settings().filter(|s| categories.contains(&s.category)) { match descriptions::DESCRIPTIONS.iter().filter(|(k, _)| *k == s.key).count() { 1 => {} n => bad.push(format!("`{}` ({}) has {n} sentences", s.key, s.label)), @@ -2125,6 +2158,53 @@ fn keyboard_focus_on_a_smart_guides_row_shows_its_description() { assert!(described.iter().any(|d| d == smart), "the focused control carries the sentence: {described:?}"); } +/// The pointer over Slices' Show Slice Numbers row and over its Line Color row shows each row's +/// sentence. +#[test] +fn hovering_a_slices_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Slices")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let numbers = descriptions::description("showSliceNumbers").expect("Show Slice Numbers has a sentence"); + let color = descriptions::description("sliceLineColor").expect("Line Color has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Show Slice Numbers"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, numbers) && !painted(&after, color), "the Show Slice Numbers row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Line Color:"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, color) && !painted(&after, numbers), "the Line Color row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches Slices' first control, the Show Slice Numbers box: the line +/// shows its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_slices_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Slices")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let numbers = descriptions::description("showSliceNumbers").expect("Show Slice Numbers has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, numbers) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Show Slice Numbers row and its sentence shows"); + assert!(described.iter().any(|d| d == numbers), "the focused control carries the sentence: {described:?}"); +} + /// A sentence shown when the dialog closed does not come back when it opens again with the /// pointer away from the rows. #[test] diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 25eb47503b..e6120ad599 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1017,14 +1017,10 @@ fn names_a_required_field(params: &str) -> bool { !(f.is_empty() || f.starts_with('…') || f[end..].starts_with('=') || f[..end].split('|').all(|n| n.trim().ends_with('?'))) }; let Some(rest) = params.strip_prefix('{') else { return false }; - let (mut depth, mut quoted, mut start) = (0usize, false, 0); - for (i, ch) in rest.char_indices() { + let mut start = 0; + for (i, ch, depth) in outside_quotes(rest) { match ch { - '"' => quoted = !quoted, - _ if quoted => {} - '{' | '[' | '(' => depth += 1, '}' if depth == 0 => return required(&rest[start..i]), - '}' | ']' | ')' => depth = depth.saturating_sub(1), ',' if depth == 0 => { if required(&rest[start..i]) { return true; @@ -1037,6 +1033,29 @@ fn names_a_required_field(params: &str) -> bool { false } +/// Each character of `text` that is not a double quote or inside a pair of them, with its byte +/// offset and the number of `{`, `[` and `(` groups open before it. A closing `}`, `]` or `)` comes +/// with a count that includes the group it closes, and one with no group open counts none. +pub(crate) fn outside_quotes(text: &str) -> impl Iterator + '_ { + let (mut depth, mut quoted) = (0usize, false); + text.char_indices().filter_map(move |(i, ch)| { + if ch == '"' { + quoted = !quoted; + return None; + } + if quoted { + return None; + } + let before = depth; + match ch { + '{' | '[' | '(' => depth += 1, + '}' | ']' | ')' => depth = depth.saturating_sub(1), + _ => {} + } + Some((i, ch, before)) + }) +} + pub fn entry(key: &str) -> Option { entries().iter().find(|e| e.key == key).cloned() } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8790fc9280..79b35e9392 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -219,6 +219,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ ("colorThemes", "Color Themes", "sun"), (crate::panels::color_wheel::ID, "Color Wheel", "circle"), (crate::panels::links::ID, "Links", "link"), + (crate::panels::preflight::ID, "Production Preflight", "dc-list-view"), (crate::panels::asset_export::ID, "Asset Export", "share-2"), (crate::panels::css_properties::ID, "CSS Properties", "globe"), (crate::panels::three_d::ID, "3D and Materials", "dc-cube"), diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 93f0117eb8..02c077e9af 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -520,7 +520,9 @@ fn a_slow_first_read_says_so_until_its_listing_comes() { scripts_menu::check_slow(started + scripts_menu::SLOW_SECS / 2.0); assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); assert_eq!(scripts_menu::revision(), before); - scripts_menu::check_slow(started + scripts_menu::SLOW_SECS); + // Past the threshold rather than at it: `(started + SLOW_SECS) - started` can round below + // SLOW_SECS, which made this test fail for some start times. + scripts_menu::check_slow(started + 1.5 * scripts_menu::SLOW_SECS); assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::SLOW)); assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::SLOW)); assert_eq!(scripts_menu::revision(), before + 1); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index ec2ef99db0..261905f642 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -298,6 +298,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, cols: usize, floating: Option, key: &str) -> egui::Id { /// One icon button per tool, the active one lit, with its name and shortcut on hover. Returns the /// tool clicked and the button of `locate`. -fn tool_strip(ui: &mut Ui, t: &Tokens, active: &str, tools: &[String], locate: Option<&str>) -> (Option<&'static str>, Option) { +fn tool_strip( + ui: &mut Ui, + t: &Tokens, + active: &str, + tools: &[String], + toolbar: Option<&str>, + locate: Option<&str>, +) -> (Option<&'static str>, Option) { let mut chosen = None; let mut located = None; for tool in tools.iter().filter_map(|id| tool_info(id)) { let (r, resp) = ui.allocate_exact_size(STRIP_BUTTON, Sense::click()); + crate::palette::note_spot(ui, r, || crate::palette::SpotAt::Strip(toolbar.map(str::to_string), tool.id.to_string())); let well = r.shrink(1.0); if active == tool.id { ui.painter().rect_filled(well, CornerRadius::same(6), t.tool_active); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 12c9c37dd0..45818730d1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -51,8 +51,8 @@ pub use drag::{ use dropdowns::combo_button_id; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ - dropdown, dropdown_icon_names, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, - menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, + dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, + dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, }; #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index 315bdf0366..e0eec69ecd 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -17,7 +17,8 @@ pub enum PanelDrag { /// replaces the style it is dropped on with it (`graphicStyle.redefine`). Appearance(vectorcraft_doc::NodeId), /// A Graphic Styles panel style: art it is dropped on takes it (`graphicStyle.apply` with its - /// `ids`); the panel moves it to where it is dropped. + /// `ids`); the panel moves it to where it is dropped, or with Alt held replaces the style it is + /// dropped on with its look (`graphicStyle.redefine` with `from`). GraphicStyle(String), /// The selected art, dragged off the canvas with the Selection tool: the Graphic Styles panel /// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 7f088f25ef..1b2d4b421f 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -50,11 +50,23 @@ pub fn dropdown_icon_names( width: f32, icon_size: f32, icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), +) -> Option { + dropdown_icon_names_sized(ui, id, current, options, width, Vec2::splat(icon_size), icon) +} + +/// [`dropdown_icon_names`] with icons of any size, for a picture wider than it is tall, such as a +/// line with an arrowhead. +pub fn dropdown_icon_names_sized( + ui: &mut Ui, + id: impl std::hash::Hash, + current: Option, + options: &[&str], + width: f32, + icon_size: Vec2, + icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), ) -> Option { let icon = &icon; - let atom = move |i: usize, highlighted: bool| { - egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)) - }; + let atom = move |i: usize, highlighted: bool| egui::Atom::paint(icon_size, move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)); let shown = match current.and_then(|i| options.get(i).map(|name| (i, *name))) { Some((i, name)) => (atom(i, false), egui::RichText::new(name).size(12.0)).into_atoms(), None => egui::RichText::new("").size(12.0).into_atoms(), diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index c6c241e504..0b89811929 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -524,3 +524,28 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { assert_eq!(typed(automatic, "(1,5)"), Some(SpinPick::Value(1.5)), "a decimal comma, automatic: {automatic}"); } } + +/// Enter on text that reads as no number in a range field refuses it as a unit field does: the +/// field flashes and an open dialog is not confirmed with the old value. +#[test] +fn a_range_field_refuses_text_that_reads_as_no_number() { + let typed = |text: &str| { + let ctx = themed(Default::default()); + let picked = std::cell::Cell::new(None); + let mut add = |ui: &mut Ui| { + if let Some(v) = range_field(ui, "count", 12.0, 0.0..=100.0, "", 0, 80.0) { + picked.set(Some(v)); + } + }; + arm_field_focus(&ctx, "count"); + frame(&ctx, 0.0, vec![], &mut add); + frame(&ctx, 0.1, vec![], &mut add); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&ctx, 0.2, vec![egui::Event::Text(text.into()), enter(true), enter(false)], &mut add); + let refused = ctx.data_mut(|d| d.remove_temp::(dialog_reject_commit_flag())).unwrap_or(false); + (picked.get(), refused) + }; + assert_eq!(typed("40"), (Some(40.0), false), "a number commits"); + assert_eq!(typed("abc"), (None, true), "text that reads as no number is refused"); + assert_eq!(typed("(10+5)*2"), (None, true), "parentheses the field doesn't read are refused"); +} diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 01ce18757f..a9d4020ab3 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -917,7 +917,19 @@ fn bounded_field_reading( let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals)); let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds); if commit && buf != shown { - read(&buf) + let typed = read(&buf); + if typed.is_none() { + // Text that reads as no number is refused as [`unit_field_from`] refuses it: the field + // flashes, shows its value again, and an open dialog is not confirmed by this Enter. + let end = ui.input(|i| i.time + 0.25); + ui.data_mut(|d| { + d.remove::(id); + d.insert_temp(id.with("invalid-flash"), end); + }); + crate::widgets::reject_dialog_commit(ui.ctx()); + ui.ctx().request_repaint(); + } + typed } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) { Some(v) } else if live && resp.changed() { diff --git a/docs/dimensions.md b/docs/dimensions.md index 35e164d4f9..762575379b 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -51,6 +51,11 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers point as before. An unlinked dimension that turns has its line where the turn puts it, or, when that would put it between the points, as far past the outermost point as before. + With Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping + tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn + anywhere in the document has its line on that level. This is VectorCraft's own rule. With + Alignment Guides on, a guide runs along the level across both lines while the dimension is + placed. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 91af8cd7b3..36e73837d8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.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; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; 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; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.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; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; 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; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **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). @@ -315,7 +315,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) 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. | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X; the document language as the catalog's `/Lang` and XMP `dc:language`, #3644) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) 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. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | @@ -383,6 +383,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 5dee50afa1..e956b899e0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,9 +1,11 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; 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: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; 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; estimate 1–2 h → 0; 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: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; 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, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); 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; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; 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; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; 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: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; 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; estimate 1–2 h → 0; 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: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; 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, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); 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; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; 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; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. +> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. + ## Feature submission evidence **Feature evidence last updated:** 2026-11-15. @@ -36,6 +38,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G19: PDF export writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, in exported and printed PDFs (#3644); `/MarkInfo` stays with tagged PDF (#3643). Scores and estimates unchanged. | | 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | @@ -332,6 +335,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools +- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. + - **Export-only improvement (#6309):** 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. Broader G11 scope, scores and estimates unchanged. - **Done, deletion only (#3380):** deleting anchors or segments that disconnect an ordinary contour creates independent selected path objects, preserving appearance, baked transforms, sibling order and one-step Undo/Redo. Existing multi-subpath paths and compound members stay intact. A second Delete removes all selected survivors. Bounds-fitted gradients keep their original placement on the new objects; already placed gradients stay unchanged. Segment endpoint highlighting remains open; broader G11 scope, scores and estimates are unchanged. Evidence: `crates/engine/tests/it/delete_path_pieces.rs` and the Delete/Backspace frame regression in `crates/ui-egui/src/tests/removeanchors.rs`. @@ -477,6 +482,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Production workflow addition (2026-11-18):** Window > Production Preflight brings existing output-aware font/overflow checks, linked-file probes and effective image resolution into one panel. Findings select and zoom to affected art, and results recheck after edits, Undo/Redo and external link changes. Resource-art resolution is explicitly not checked. This does not close the remaining G12 gaps or change estimates. + - **Implemented and tested (2026-11-15):** Swatches list rows and thumbnail cells have item context menus with Swatch Options…, Duplicate Swatch and Delete Swatch. Right-click selects the target without painting art; actions use that item's name and are disabled for reserved or missing swatches. All 39 Swatches tests pass, covering all five views, command dispatch, selection and Undo; the regression fails with the menu hooks removed. Rendered list and thumbnail menus were inspected. 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. Other panels without context menus remain in G12; estimate unchanged. - **Done (2026-11-14):** Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu with Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of the symbol), and Select All Instances, selecting the symbol if unselected. Estimate unchanged. @@ -675,7 +682,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (ten original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes (one + its own (eleven original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes) and Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo @@ -869,7 +876,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** AccessKit is on by default, so egui widgets reach screen readers, but custom panels, the canvas and its objects aren't described and nothing has been tested with VoiceOver, Narrator or Orca; keyboard-only canvas operation; high contrast. Illustrator's own accessibility is limited, so this is mostly beyond parity. -- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). +- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). It writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, so screen readers and checkers know the language (#3644). Tagged PDF (structure tree, `/MarkInfo`) is still missing (#3643). - **Estimate:** 15–25 h. ## Highlighted-text Eyedropper (2026-10-21) @@ -909,6 +916,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-14 | minor | Type: Middle Eastern & South Asian and Standard composers per paragraph (#4935): Paragraph panel menu, paragraph styles, `text.setFormat {composer}` and the native file; the Standard composers set Indic, Arabic and Hebrew type glyph by glyph. `.ai`, EPS and PDF files carry no composer. 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. | @@ -916,6 +924,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 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. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | | 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | +| 2026-11-12 | minor | Blend redraw (#5179): renderer bounds include spine-placed keys and steps. Original straight and curved Replace Spine, move and Undo CPU regressions pass; scores and estimates unchanged. | | 2026-11-09 | minor | G4 review (#6084): positional variants no supported feature draws can be applied as glyph choices in both Glyphs views; unlisted glyphs still respect name ownership. OpenType style options keep only a valid last on-value when enabling a set. Existing contextual/ligature lookup and unsupported-feature gaps remain; estimate unchanged. | | 2026-11-07 | minor | G4: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to that letter alone (`salt=2`; the style commands take `tag=N`; runs that differ only in their features shape as one piece of text), so an Arabic word stays joined, and Show › Entire Font lists the unencoded glyphs (#5514). Estimate unchanged. | | 2026-11-12 | minor | G11: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); short-drag and jitter-tap regressions in `tests/numfields.rs`; estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 2a71579399..8fbc770ca7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-14 · **Change:** `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-11-18 · **Change:** Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). @@ -286,6 +286,16 @@ the suite) keep the agent to the folders you give it: linked native document with `relink: false`, as it is: when the native document such a file is or carries keeps a folder outside the read roots, the package is refused before anything is written with "a linked file's export folder is outside the read roots", which names no file or folder. +- An exporter plug-in's format (`plugin.`) carries the native document too: its plug-in is given the + document's JSON. The JavaScript and linked image rules above refuse its files from every command that writes + them, before the plug-in runs and before any file or folder is written, and the JSON the plug-in is given + leaves out an Export for Screens folder outside the read roots. +- `file.package` refuses, before anything is written, a linked file whose native document it can't read to + check against the read roots: a native document that doesn't load, a PDF or `.ai` file that can't be opened + (one that needs a password to open, or a damaged one), and a PDF, `.ai` or EPS file whose editing data + doesn't load. The error, "a linked file's editing data can't be read to check it against the read roots", + names no file or folder. A PDF, `.ai` or EPS file without editing data is copied as before, and the person at + the keyboard packages every linked file as before. - `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` @@ -714,7 +724,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is not a number, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers; a null `reflect`, `copy` or `origin` is left out. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | @@ -3657,7 +3667,13 @@ already walks Image Trace. Short agent entry points: - Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic`, `type`: `static`|`dynamic` and `alignToPixelGrid`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?}`, + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?, keepArt?: false}` + (New Symbol: the selection, or `ids`, becomes the symbol's art and an instance of it in one undo step; with + `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected unless it is hidden or + locked, and the result's `id` is null; a `keepArt` other than true or false is an error; the Symbols panel sends + `keepArt: true` when its New Symbol button, with or without Alt, or its New Symbol… menu item is used with Shift + held, through Symbol Options' OK (`ui.symbolOptions {keepArt: true}`), and when art dragged off the canvas is + released on the panel with Shift held), `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 @@ -4615,8 +4631,14 @@ object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the obj style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}` updates only the objects still linked. Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a style in the Graphic Styles panel with Alt held runs `graphicStyle.redefine` with that style's `name` and the object's -`id` (the first object of the art); an object already linked to the style with its look changes nothing. The art of a -column or marker design in a graph series is never linked: +`id` (the first object of the art); an object already linked to the style with its look changes nothing. +`graphicStyle.redefine {name, from}` gives the style `name` the look of the style `from` instead (fills, strokes, +effects, opacity, blend mode, isolate and knockout): `name` keeps its name, place and id, its objects still linked +follow in one undo step, and `from` and its objects stay as they are. `from` naming the same style, or a style with +the same look, records nothing; a `from` that names no style or is not a string, or `from` with `id`, is an error. A +style dragged onto another in the Graphic Styles panel with Alt held runs it with the dragged style as `from`; +without Alt the style moves (`graphicStyle.move`). The art of a column or marker design in a graph series is never +linked: `graphicStyle.new` can make a style from it, and `graphicStyle.redefine` leaves its look as it was and unlinks it, whether it is the source or a linked object. `graphicStyle.list` returns each style with the ids linked to it and the style of the first selected object; `select.same.graphicStyle` selects an object's fellow users. @@ -5385,7 +5407,7 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: ten generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle +Brush libraries are read-only sets of brushes: eleven generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has @@ -5418,7 +5440,10 @@ and several can be open at once. `window.swatchLibrary {library}`, `window.graph `{open, panel, name, count}`; `library: null` closes every panel of that kind. The panel id is `library::` (`library:swatches:pastels`, `library:graphicStyles:hand-drawn`, `library:swatches:loaded/C:/Palettes/Brand.ase`), and the panel commands take it like any other panel's: -`window.panel.float {panel, onto?, x?, y?}` groups or moves it, `window.panel.dock {panel}` docks it, +`window.panel.float {panel, onto?, x?, y?, width?, height?}` groups, moves or resizes it. Supplied +geometry also updates an existing native panel window. Positions are relative to the main window's +content origin; omitted coordinates and dimensions keep the native window's current values. +`window.panel.dock {panel}` docks it, `window.panel.close {panel}` closes it. `window.swatchLibrary.other {path}`, `window.graphicStyleLibrary.other {path}`, `window.symbolLibrary.other {path}` and `window.brushLibrary.other {path}` load a file and open it the same way. @@ -6752,8 +6777,9 @@ and Shift steps follow the box the same way; a Reflect axis drawn with the tool line on the page at that angle, counter-clockwise from horizontal, as `object.reflect`'s numeric `axis` is, and the art slides along that line about `origin` by the shear `angle`, which stays a separate value. 0 shears as `"horizontal"` and 90 as `"vertical"`. A numeric `axis` outside the range, a number given as a string, or any other value is an -error, and nothing changes. The shear `angle` is clamped to -89 through 89. The Shear dialog's Axis has Horizontal, -Vertical and Angle; the Axis Angle field beside it starts at 0° and takes input while Angle is chosen. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) +error, and nothing changes. The shear `angle` runs from -359 to 359 along every axis and is sheared by its tangent; +±90 and ±270 are an error. The Shear dialog's Axis has Horizontal, Vertical and Angle; the Axis Angle field beside it +starts at 0° and takes input while Angle is chosen. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) describes the Angle axis as a custom slant direction between -359° and 359°, measured from the horizontal. The counter-clockwise direction on the page and the 0° starting value are VectorCraft's own. @@ -7272,8 +7298,12 @@ wide. `object.align` needs `horizontal` or `vertical`. The three Align commands, `object.reflect` and `object.shear` return an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or `bounds` param given another value (`object.reflect` and `object.shear` also take a numeric `axis` and name the value given; `object.shear`'s numeric -`axis` runs from -359 to 359, while its `angle` is clamped to -89 through 89), and one for a `spacing` that is not a -number; nothing moves. +`axis` runs from -359 to 359), and one for a `spacing` that is not a number; nothing moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the +[Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), +and shears by its tangent, so 120 slants as -60. An angle of 0 or ±180 (within 1e-9 degrees) has no slant: without +`copy`, nothing moves and no undo step is recorded, and with `copy` the copies keep the art's place. It returns an error for an angle outside that range, and, as +VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo +step is recorded. ## Glyph bounds for type @@ -9195,6 +9225,21 @@ Screens doesn't write EPS. {"name":"export","arguments":{"path":"/tmp/art.eps","options":{"useArtboards":true,"cmykPostScript":false}}} ``` +## Production Preflight + +`document.preflight {output?: "pdf"|"print"|"screen", minPpi?: 1..9600, artboards?: [index, …]}` +checks the active document without editing it or writing an export. Defaults: PDF, 300 ppi +(96 ppi for Screen), all artboards. Indices are zero based. Print uses the saved Print settings +with the requested artboards, including page scaling; PDF and Screen check visible art on them. + +The result contains `checks` for `fonts`, `text`, `links` and `resolution`, each with `status` +(`passed`, `failed`, `notChecked`), finding `count` and `notChecked` count. `findings` give a +`code`, canvas `ids` and `name`; link findings also carry `sourceId`, and resolution findings +carry `effectivePpi` and `threshold`. `outputWarnings` carries the Print preview's output/settings +warnings. Resource findings point to their first visible canvas owner. Resolution inside resource +art or placed documents is explicitly not checked; a pass is not certification of an exported file. +See [Production Preflight](production-preflight.md) for the panel and coverage limits. + ## Print File → Print lays the job out as a print-ready PDF, in which each page is a sheet of the chosen paper. The desktop app @@ -9541,7 +9586,7 @@ File → Export → Save for Web (Legacy) writes optimised web images: `document …}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at `width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`, `dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked, -transparent, webShift, sort, deleted, customPalette}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 +transparent, webShift, sort, deleted, customPalette, shifted}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 `transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `` is the name of `path` without its extension, or without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after @@ -9554,7 +9599,7 @@ couldn't be decoded and is missing from the image; the files are written all the `document.exportForWeb.preview` returns what Save writes for the same settings without writing it: `bytes` (the exact file size), `seconds` to download at `kbps` (default 56.6), the size, and for palette formats the colour table -(`colors: [{color, source, transparent, locked, webShifted, webSafe}]`). The colour table's lists name colours by +(`colors: [{color, source, transparent, locked, webShifted, shifted, webSafe}]`). The colour table's lists name colours by `source` (the colour the reduction made), so a colour keeps its edits when it is web-shifted or snapped. `slice: n` previews one slice; `image: true` adds the file; `warnings` holds the export's warnings. @@ -9564,15 +9609,38 @@ file agree. A deleted color also leaves `locked`, `transparent` and `webShift`. ignored. Deleting every opaque color is an error, and the settings, preview and files do not change; the transparent entry of transparent pixels cannot be deleted. `colorTable.customPalette: ["#rrggbb"…]` is a fixed palette (a Custom table) used instead of the reduction's own, at most `colors` entries with the transparent one included, so a color it -lacks is not made again; the dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold +lacks is not made again. Its colors in `transparent` all become the transparent entry and take one of the `colors` +slots together (when no pixel is transparent and no pixel takes one of them, that slot goes to its next color); its +other colors fill the remaining slots in order. The dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold at most 256 colors, and `#rrggbbaa` is refused. A `reduction` change without `colorTable` in the same params clears both lists. JPEG and PNG-24 have no color table and do not read them. Presets and `webExport.settings` keep them. In the dialog a click selects one color, Shift-click selects the colors between it and the last one clicked, and Ctrl-click (Command-click on macOS) adds or removes one (`__colors` holds the selection, `__color` the last one -clicked). The trash button and Delete Color in the table's menu delete the selection in one edit, Restore Generated +clicked). The trash button and Delete Color in the table's menu delete the selected colors the table shows in one edit, +and are off when it shows none of them (a selected color can leave the table when the reduction or the color count +changes). The Lock, Transparent and Web Shift buttons act on the last color clicked, and are off when the table no longer +shows it. Restore Generated Table in that menu clears `deleted` and `customPalette`, and the table reads Custom while either is set. Choosing another reduction in the dialog also clears them. +Shifting a color is `colorTable.shifted: {"#source": "#rrggbb"…}`, by `source`: every pixel of that color is +written as the color given, in the preview and the file. The color is kept when the colors are reduced, as a +locked one is: the shifted and locked colors take the palette's slots first, shifted ones before locked ones, and at +least one slot is left for the reduction, so with `colors: 2` and transparent pixels none is kept and a color left out +shifts nothing. As with a locked color, a kept source stays in the palette when the art no longer has it, and the +pixels nearest to it are written in the new color. The preview marks it `shifted` and `locked`. A shift by hand wins over `webShift`, `webSnap` and +`locked`; a color mapped to transparent stays transparent. GIF `lossy` moves no pixel into or out of a shifted color. +Two colors may be shifted to the same color. A source the +table does not hold shifts nothing, and the shift stays with the settings for when it comes back; another reduction +keeps it. The settings store the map in lowercase, drop a color shifted to itself or deleted, and drop the `webShift` +of a color shifted by hand. More than 256 entries, a key or value that is not a color such as `#ff8800` (`#rrggbbaa` +included), and two keys that name one color are errors. Presets and `webExport.settings` keep the map. In the dialog a double-click on an +opaque swatch opens the Color Picker on the color shown (on the source color for a color already shifted; an agent +sets `__editColor: "#source"`). Its OK shifts the color (picking the source color takes the shift away), and Cancel +leaves the table as it was. A shifted swatch shows the source color at its upper left and the new color at its lower +right, with the lock mark, and Lock stays on until the color is unshifted. Web Shift replaces a shift by hand, and +Unshift All Colors in the table's menu clears `shifted` and `webShift`. Only Web Colors in the picker starts off. + ```json {"name":"run_command","arguments":{"command":"document.exportForWeb.preview","params":{"format":"png8","colorTable":{"deleted":["#ff0000"],"customPalette":["#0000ff","#00ff00","#ff0000"]}}}} ``` @@ -10367,7 +10435,7 @@ thread. When `effect.expandAppearance` keeps a frame as type in a group (type wi effects are shadows, outer glows or Crop Marks), the type stays in the thread in the frame's place. Object › Expand (`object.expand`) outlines type with these two commands. `object.flattenTransparency` takes each frame of threaded text that it outlines (`textToOutlines`) or turns into flat regions or an image out of its thread in the same way. -`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol, without `keepArt: true`) take each frame of threaded text in the selection out +`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol), without `keepArt: true`, take each frame of threaded text in the selection out of its thread in the same way, and the symbol's art holds a copy of the frame with the text it shows. When every frame of a thread goes into the symbol, the copy of the last frame keeps the text it has no room for. @@ -11902,6 +11970,10 @@ no file, and an import opens no document). A filter whose manifest asks for a he `plugin.inspect {path | dataBase64}` entry) needs a person's approval, and `plugin.install` refuses `allowHeavy: true` from a request. `plugin.run` runs it where it is called, so the call may take minutes; `notifications/cancelled` stops it. +The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `prefs.set` refuses any other value) +sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M, +plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with +either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)). A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, @@ -11994,6 +12066,7 @@ Disable and Continue can't save the plug-in it turns off, this launch skips it a {"name":"run_command","arguments":{"command":"plugin.setEnabled","params":{"id":"org.example.wobble","enabled":true}}} {"name":"run_command","arguments":{"command":"plugin.install","params":{"path":"/plugins/desaturate.wasm"}}} {"name":"run_command","arguments":{"command":"plugin.run","params":{"id":"org.vectorcraft.example.desaturate","params":{"amount":60}}}} +{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"pluginInstructionBudget","value":"large"}}} {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"plugin.org.example.wobble","params":{"size":4}}}} {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/plot.hpgl","importer":"plugin.org.example.hpgl"}}} {"name":"run_command","arguments":{"command":"plugin.org.example.tidy.grow","params":{"by":3}}} @@ -13338,18 +13411,26 @@ Commands: where it touches the upper one; where a straight side of a path lies along the line, the line covers the whole side. An ellipse drawn with the Ellipse tool, then moved, turned or scaled, is measured as an exact ellipse. Any other path must be closed, have one outline, bend the same way all around and have at most 10,000 segments; an open - path, a path that bends inward, a path without area, a group, a compound path or type is refused, and so are two - paths whose outlines are the same to within the touching tolerance given below. Two separate paths have two - external and two internal tangents. Overlapping paths have external tangents only. A path inside the other has - none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point - where they touch and as long as the narrower path is wide along it. Paths that meet at a corner or along a shared - stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when - the gap between them is less than the tolerance, a billionth of the larger of their sizes and the distance between - their centers. The lines are stroked with the current stroke color and weight (black when the stroke is None), have - no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of - the kind asked for, nothing changes, and the result's `warning` says why. Common Tangents… - opens a dialog (Tangents, Centerline) with Preview. → `{ids, external, internal, centerline, warning?}` - (`centerline`: the centerline's id, or null). + path, a path that bends inward, a path without area (other than a point, described below), a group, a compound + path or type is refused, and so are two paths whose outlines are the same to within the touching tolerance given + below. Two separate paths have two external and two internal tangents. Overlapping paths have external tangents + only. A path inside the other has none. Paths that touch, from outside or from inside, share one tangent there + instead: a line centered on the point where they touch and as long as the narrower path is wide along it. Paths + that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that + touch both. Paths count as touching when the gap between them is less than the tolerance, a billionth of the larger + of their sizes and the distance between their centers. One of the two may be a point instead, a path of one + anchor: the lines then run from the point to where they touch the path, two when the point lies outside it (one + that lies along a straight side covers the whole side), one when the point lies on its outline (centered on the + point and as long as the path is wide along it, or the whole straight side the point lies on), and none when it + lies inside. The point counts as on the outline when it is less than the touching tolerance from it, with the + point's distance from the path's center in place of the distance between centers. Every `tangents` value gives + the same lines, counted in `internal` when `tangents` is `internal` and in `external` otherwise; the centerline + runs from the point to the path's center. Two points are refused with "select two closed paths". The lines are + stroked with the current stroke color and weight (black when the stroke is None), have no fill, go directly above + the upper of the two paths and are selected; one undo step. When there is no tangent of the kind asked for, + nothing changes, and the result's `warning` says why. Common Tangents… opens a dialog (Tangents, Centerline) with + Preview; with a point selected, every Tangents choice gives the same lines. → `{ids, external, internal, + centerline, warning?}` (`centerline`: the centerline's id, or null). A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; @@ -14327,6 +14408,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| +| 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. | | 2026-11-14 | Built-in Tech Circuit brush library (id `tech-circuit`): Circuit Trace, Bus Lines and Terminal Nodes; ten built-in libraries. | | 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). | | 2026-11-13 | `path.freehand`: `closed`, when given, decides whether a stroke that continues a path (`extend`) closes it; the Pencil and the Paintbrush send it by Close Paths When Ends Are Within. | diff --git a/docs/plugins.md b/docs/plugins.md index 2702e4fe7b..344e3b7c00 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -126,7 +126,7 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | | Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | @@ -136,6 +136,22 @@ An export runs where the export runs: with Background Export on, on the export's plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. +### Instruction budget preference + +Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`, VectorCraft's own +setting) sets the instructions each object filter run gets, from the app, `plugin.run`, a plug-in's commands, scripts +and MCP alike: + +- **Normal** (`normal`, the default): the limits in the table above, 50 M + 4,000 per input byte. +- **Large** (`large`): 250 M + 4,000 per input byte (`vectorcraft_plugins::LARGE_FUEL`, 5 times Normal). The 60 s time + budget, the memory, output and call depth limits stay as they are. + +A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep +their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and +the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +"pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other +value; a saved preferences file with another value reads as Normal. + ### Live effects while a document opens While the app draws a document on screen, the live-effect runs of its first view share a 2,000 ms budget diff --git a/docs/production-preflight.md b/docs/production-preflight.md new file mode 100644 index 0000000000..ecc551f0c9 --- /dev/null +++ b/docs/production-preflight.md @@ -0,0 +1,99 @@ +# Production Preflight + +Open **Window > Production Preflight** before delivering artwork. Choose **PDF**, **Print** or +**Screen**, set the minimum image resolution, and optionally check only the active artboard. +The default minimum is 300 ppi for PDF/Print and 96 ppi for Screen. These are editable workflow +defaults, not a guarantee of suitability for a particular printer or display. + +The panel checks: + +- **Fonts:** unavailable font families and styles that will use a fallback or a substitute. +- **Text Overflow:** area type or type on a path whose text extends beyond its frame. +- **Linked Files:** missing files and files that changed since they were read. +- **Image Resolution:** effective resolution along both pixel axes at the image's placed size. + Print includes the job's page transform, so enlarging the print can lower effective resolution. + +Click a finding to select and zoom to the affected artwork. A font finding can select several +objects. A finding inside a symbol, pattern, brush or opacity mask locates its first visible +canvas owner. If some artwork cannot be selected, the status bar reports it; any selectable +objects are still located without unlocking artwork or artboards. **Find Font…**, **Relink…** and +**Update Link** open the existing repair workflows; +they do not apply an automatic font substitution or change artwork just by checking it. + +Results refresh after document edits, Undo/Redo, document switches and changes to the panel's +options. During an interaction the panel waits for the edit to finish. External files are +checked again every two seconds while the panel is visible; **Recheck** runs immediately. + +PDF and Screen inspect visible artwork intersecting the chosen artboards. Print reuses the saved +Print settings with the chosen artboards, including which layers print and what fits on the +sheet; it also shows the existing print-preview geometry/settings warnings. Locked artwork is +still checked because locking it does not prevent output. Hidden artwork is checked only if the +Print settings include hidden layers. + +## Coverage limits + +This is a check of the document and selected output context, not validation or certification of +an exported file. PDF export presets, colour conversion, ink coverage, bleed adequacy and +accessibility compliance are not checked by this first version. + +Resolution inside symbols, patterns, brushes, opacity masks and placed documents is reported as +**Not checked**, because the resource's local transform alone does not establish its final output +resolution. A resolution check with both findings and unchecked art shows **Needs attention** +and also states that some art was not checked. A vector placed document has no single bitmap PPI. + +The font and text checks share the existing output-aware walk, including its bounds/clipping +approximations for generated art and container effects. Resource findings identify a representative +visible owner, not an exhaustive list of every instance. A passed check means only that no problem +of that kind was found within the stated coverage. + +The same read-only report is available through `document.preflight`; see [MCP](mcp.md#production-preflight). + +## Validation (2026-11-18) + +Checked on Windows with Rust 1.99.1, based on `main` at `36b5a5920c`: + +- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test preflight`). +- Panel tests: 5 passed (`cargo test -p vectorcraft-ui-egui --lib preflight`), including pointer + selection/zoom, edits and Undo, document switching, external-file polling and explicit Recheck. +- Both test commands used `--offline --target-dir target --config profile.test.opt-level=0`. +- Existing Print Preview and Links panel engine regressions: 16 + 16 passed, run from the native + engine test binary with filters `tests::printpreview` and `tests::linkspanel`. +- The ignored `preflight_panel_preview` test was run explicitly, rendered through the offscreen GPU + harness and visually inspected. Its output remains under the ignored `target/` directory. +- Native Clippy for the engine and UI, all targets, passed with `-D warnings` (explicit + `--target x86_64-pc-windows-msvc`, using `target/wasm-check` for the validation artifacts). +- Engine/UI WebAssembly typecheck passed. Formatting, asset attribution, branding, dependency + layering and PDF dependency checks passed. +- Windows desktop build passed (`cargo build -p vectorcraft --offline --target-dir target + --config profile.dev.opt-level=0`). The running panel was visually inspected with a sample + exercising all four findings, and the contributor tried it in the desktop app. + +`cargo xtask ci` was attempted with `CARGO_BUILD_TARGET=x86_64-pc-windows-msvc`: formatting and +workspace Clippy (all targets, `-D warnings`) passed. It was stopped during workspace-test +compilation after the separate `ui-commands --check` confirmed pre-existing drift between the +unchanged `menus/ui_commands.rs` and generated `mcp/src/ui_catalog.rs`. The complete workspace +test suite and remaining CI stages were not completed. An additional +WebAssembly Clippy run also encounters existing target-specific lints in unchanged `cmd/plugin.rs` +(`drop_non_drop`) and `font_menu.rs` (`unnecessary_lazy_evaluations`); the WebAssembly typecheck and +the native Clippy run above pass without source changes for those findings. + +### Review follow-up on `main` at `ee60c51fd` + +The exact-threshold and locked-artboard regressions were first run against the original +implementation and failed. After the fixes and merge-conflict resolution: + +- All 10 engine preflight tests and 7 panel tests passed. The optional GPU preview also passed + and was visually inspected. +- The boundary regression checks several exact PPI thresholds and a real shortfall on one axis. +- Navigation regressions cover a locked artboard, retry after unlocking, and partial selection + that still zooms to the selectable artwork. Finding navigation never unlocks artwork. +- Formatting, native workspace Clippy with warnings denied, engine/UI WebAssembly typecheck, + layering and PDF dependency checks passed. The complete workspace CI suite remains incomplete; the unchanged UI command catalog + still fails its separate drift check. + +## Revision history + +| Date | Change | +|---|---| +| 2026-11-18 | Review follow-up: tolerate PPI rounding at the minimum, report incomplete finding selection, and retain main's symbol lookup improvements when resolving merge conflicts. | +| 2026-11-18 | Initial Production Preflight panel and command. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 3c09bde829..1dcbf6413c 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-17 · **Change:** minor (M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #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). > @@ -14,6 +14,8 @@ > **PDF import status (2026-11-14, #6957):** Outlined Indic glyphs retain their full stroke properties; translucent glyphs stay separate, and a soft mask attaches to each glyph separately. Scores and estimates unchanged. +> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. + > **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. ## Feature submission evidence @@ -59,6 +61,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M14: PDF export writes the document language (Document Setup) as the catalog's `/Lang` (#3644). Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | @@ -160,20 +163,20 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); hidden-fill and no-fill stroke cap/join CPU regressions passed; 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 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; 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 (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); 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: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; estimates unchanged); 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) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; estimates unchanged); 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 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | -| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | +| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, eleven generated libraries including Tech Circuit, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -215,6 +218,8 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | +| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | M1: an Alt-drag in the Layers panel copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | @@ -235,6 +240,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-12 | minor | M12: Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | | 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | +| 2026-11-12 | minor | Blend redraw (#5179): renderer bounds include spine-placed keys and steps. Original straight and curved Replace Spine, move and Undo CPU regressions pass; scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | M10/G5: Energy Beams built-in brush library; MCP docs catch-up; estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b7eccdf7b9..20c05dff9c 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-17 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #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). > @@ -18,10 +18,14 @@ > **PDF import status (2026-11-14, #6957):** Outlined Indic glyphs retain their full stroke properties; translucent glyphs stay separate, and a soft mask attaches to each glyph separately. Scores and estimates unchanged. +> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. + > **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. ## Feature submission evidence +`window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. + EPS embedded fonts, 2026-11-09 (#6023–#6067): the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. Evidence: `crates/eps/src/import/tests_composite.rs`, `tests_type42.rs`, `tests_cid.rs`, `tests_type1.rs`; details in [file-format-parity.md](file-format-parity.md). Numeric fields step on wheel hover without taking keyboard focus (#5949). Arrow keys still require focus; modifiers, units, limits, mixed values and existing rounding stay in the shared stepping path. Headless regressions in `tests/numfields.rs` cover hovered unfocused fields, focused fields, trackpad accumulation and panel scroll exclusion. A canvas-first/panel-second regression also checks that a field turn cannot start a canvas zoom glide when the pointer enters the canvas on the next frame. Scores and estimates unchanged. @@ -63,6 +67,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Hardening: PDF export writes the document language (Document Setup) as the catalog's `/Lang` and XMP `dc:language` (#3644). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | @@ -257,12 +262,12 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | 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% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; 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) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (eleven generated libraries including Tech Circuit, Pressure Sensitive, 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 | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | @@ -282,9 +287,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | -| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | +| Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid and Smart Guides setting on hover and keyboard focus (#8199, #8223, #8248), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides and Slices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -526,7 +531,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill 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); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (ten generated in code including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (eleven generated in code including Tech Circuit, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -539,17 +544,17 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | -| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | +| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already; a marquee leaves locked or hidden guide paths out inside groups too, #8538) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | | File formats | 6 | 85% | PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); 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); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | -| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | +| Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | | UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 13 Preferences options stored but not yet acted on (#394: Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | | UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes, the canvas context menu and docking panels into any dock group by dragging (as tabs, a top/bottom split or icons) are done; remaining: Properties per context, Consolidate All Windows, floating panels outside the app window, context menus in the panels that have none, about 14 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | | Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, art and swatches dragged in added where they are dropped, and items shown as icons or in a list with their names, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | -| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); real-distro installation/start-up QA pending | 50–80 | +| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); PDF exports give the document language as the catalog's `/Lang` (#3644); real-distro installation/start-up QA pending | 50–80 | | **Full parity** | | **~56%** | | **~320–500** | _Inventories (2026-10-07):_ 13 menu items still stubbed (`todo(…)` in `crates/ui-egui/src/menus.rs`); every tool @@ -578,7 +583,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries ten (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries eleven (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -590,9 +595,13 @@ since 2026-10-01. ## Evidence: what ships today, by area +**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. + - `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). - Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). +- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. + - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. @@ -635,7 +644,9 @@ since 2026-10-01. **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. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. +**Drawing tools, Dimension tool lines line up with dimensions already drawn (#8063, #5590):** By VectorCraft's own rule, with Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn has its line on that level, and with Alignment Guides on a guide runs along the level across both lines while it is placed. `a_dimension_line_placed_beside_another_lands_on_its_level`, `a_dimension_line_on_another_level_shows_one_guide_across_both`, `a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer`, `a_dimension_dragged_out_beside_another_lands_on_its_level` and `a_line_the_pointer_lies_across_wins_on_one_level` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -819,7 +830,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. -- **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Slices describes its settings:** the line under the Preferences fields shows a sentence for Show Slice Numbers and for Line Color on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: each slice's number shows in a box at its top left on the canvas, the slice outlines still show with numbers off, and auto slices use a dimmer shade of the line color. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Type describes its settings:** the same line shows a sentence for each of the 23 Type settings, from Size/Leading to Measure Type by Glyph Bounds, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. Each sentence is VectorCraft's own and states what the app does with the setting: for example, which keys step by each increment, which panels show the East Asian and Indic options, and that the two pink highlights show only on screen. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. @@ -916,6 +928,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. + - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). @@ -964,6 +977,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). - Native document output and linked images under `--automation-read-root`: the outputs that carry the native document (a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard, a PDF of every artboard with Preserve Editing, also from `document.exportPdf`, the saves and Export for Screens rows) are refused, before any file or folder is written, with an error that names no file or folder, when that document names a linked image or placed file, a kept relative path or a data set's image outside the read roots, or holds a stored brush entry that does not read as a brush; files without the native document are written. Those documents, and the documents Package writes or rewrites, leave out an Export for Screens folder outside the read roots, and Package refuses a linked file it copies as it is whose native document keeps one; the open document keeps its links, data sets and folder. An Export for Screens row that writes one artboard is checked against that artboard's art, and each asset, layer or selected object writes its own native, `.ai` or EPS file. `crates/engine/src/tests/links.rs` (`confined_native_output_refuses_a_linked_image_file_outside_the_read_roots`, `confined_native_output_refuses_a_data_set_image_outside_the_read_roots`, `confined_native_output_leaves_out_an_export_folder_outside_the_read_roots`, `confined_screens_rows_check_the_artboard_each_file_holds`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root`), `crates/engine/src/cmd/fileio/tests_screens.rs` (`each_piece_writes_its_own_native_document`). + - Exporter plug-ins and Package's unreadable linked files under `--automation-read-root`: an exporter plug-in's format, whose plug-in is given the native document's JSON, is refused before the plug-in runs when that document links a JavaScript file, a linked image or placed file or a data set's image outside the read roots, and the JSON leaves out an Export for Screens folder outside them; Package refuses, before anything is written, a linked native document, PDF, `.ai` or EPS file whose native document can't be read to check it (a PDF that needs a password to open, damaged editing data), and copies a PDF or EPS file without editing data. Errors name no file or folder, and the person at the keyboard exports and packages as before. `crates/engine/tests/plugin_export.rs` (`a_confined_exporter_is_refused_stored_paths_outside_the_read_roots`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read`). - 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`. @@ -1139,6 +1153,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drag a symbol onto Delete Symbol to delete it** ([the tutorial](https://shop.smashingmagazine.com/2011/09/an-in-depth-study-of-symbols-in-illustrator-cs5/), [Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the Delete Symbol button is deleted as a click on the button deletes it (`symbol.delete`): an unused symbol asks "Delete the selected symbol?", a symbol with placed instances asks with Expand Instances, Delete Instances and Cancel, and Alt held at the release deletes an unused symbol without asking. VectorCraft's own rules: the dragged symbol is deleted, not the current one, in one undo step; a symbol that Select All Unused picked deletes every picked symbol still unused, after one question, and a symbol outside the pick is deleted on its own; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_delete_button_deletes_the_dragged_symbol_in_both_views`, `a_picked_symbol_dropped_on_delete_deletes_the_picked_symbols`, `delete_symbol_button_ignores_other_drops_and_releases_outside`. - **Alt-drag art onto a symbol to redefine it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=194), Modify a symbol instance section): art dragged off the canvas and released on a symbol in the Symbols panel with Alt (Option on macOS) held replaces that symbol's art, and every instance of the symbol updates, as Redefine Symbol does (`symbol.update` with the dragged art's `ids`). Released without Alt, the art still becomes a new symbol. VectorCraft's own rules: the symbol under the pointer is redefined, not the current one, in thumbnail view and both list views; the art becomes an instance of it, in one undo step; only that tile or row is outlined while the art is held over it with Alt; art of another document, objects the document no longer has and art that holds an instance of the symbol (directly, in an opacity mask or through the symbols it nests, which Redefine Symbol from the menu also refuses) change nothing. Tests: `panels::symbols::tests::alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step`, `alt_let_go_after_the_release_in_the_same_frame_still_redefines`, `a_plain_art_drop_on_a_symbol_makes_a_new_symbol`, `an_alt_art_drop_that_cannot_redefine_changes_nothing`, `a_secondary_button_release_drops_no_art`, `tests::brushsym::redefine_refuses_art_holding_an_instance_of_the_symbol`. - **Shift with Redefine Symbol keeps the art** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), Redefine a symbol with another object section): Redefine Symbol chosen from the Symbols panel menu with Shift held updates the symbol and every instance of it from the selected art, and the selected art stays ordinary art instead of becoming an instance (`symbol.update {keepArt: true}`). Chosen without Shift, the art still becomes an instance. VectorCraft's own rules: the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that is hidden or locked; the result has no instance id; the redefine is one undo step and, for the symbol being edited, also leaves symbol editing mode; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `tests::brushsym::redefine_with_keep_art_leaves_the_art_as_ordinary_art`, `redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `tests::symboledit::redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode`. + - **Shift with New Symbol keeps the art** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=192), Create a symbol section): holding Shift while making a new symbol from the selected art, with the Symbols panel's New Symbol button, its New Symbol… menu item or by dragging the art onto the panel, adds the symbol and leaves the art as ordinary art instead of turning it into an instance (`symbol.new {keepArt: true}`). Without Shift, the art still becomes an instance. VectorCraft's own rules: Shift is read when the button or menu item is clicked, or when the dragged art is released, and Symbol Options' OK uses it even if Shift has been let go; Shift with Alt on the button makes the symbol without Symbol Options and keeps the art; the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that cannot be selected (hidden or locked art, art in a hidden or locked group or layer, template art, art outside an isolated group, art on a locked artboard); frames of threaded text stay in their thread; the result has no instance id; the new symbol becomes the current symbol in one undo step; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `shift_new_symbol_button_keeps_the_art_with_or_without_alt`, `shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art`, `symbol_options_checks_keep_art`, `tests::brushsym::new_symbol_with_keep_art_leaves_the_art_as_ordinary_art`, `new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `cmd::threads::tests::frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread`. + - **Symbol Options button** ([Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [Create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)): the help pages list a Symbol Options control among the Symbols panel's buttons, after Break Link to Symbol and before New Symbol, and it opens the settings of the chosen symbol. The panel's bottom bar has that button, and a click opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does (`ui.symbolOptions {edit: true}`). VectorCraft's own rules: the button is disabled while the document has no current symbol, Alt-click does the same as a plain click, opening the dialog adds no undo step, and the icon is the one Swatch Options uses. Tests: `panels::symbols::tests::symbol_options_button_edits_the_current_symbol`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. @@ -1146,10 +1162,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. + - **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. @@ -1164,6 +1181,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Measure tools and Snap to Glyph:** with Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag land within the snapping tolerance on the guides of live type that the Character panel's options allow, except Anchor Point, and a Shift-drag's end slides along its 45° step to them. The guide shows during the drag. This is VectorCraft's own rule (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`); scores and estimates unchanged. - **Drawing readout without the rubber band:** with Enable Rubber Band for the Pen or Curvature tool off and Measurement Labels on, the Pen, the Smart Pen and the Curvature tool hide the preview segment but still show the D / Angle / dX / dY readout at the snapped pointer before the next click, and the Curvature tool also shows it when going on from the current end of a selected path. Measurement Labels show distance and placement while drawing ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)), and the rubber band preference turns off the path preview ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html)). Showing the readout with the rubber band off is VectorCraft's own rule (`pen::tests::measurement_label_shows_with_the_rubber_band_off`, and `the_measurement_label_shows_with_the_rubber_band_off` in `draw2::curvature::tests` and `addons::smart_pen::tests`); scores and estimates unchanged. - **Pen handle drags in the Info panel:** while a Pen drag pulls a handle out of an anchor, the Info panel shows the change in x and y (W, H), the distance (D) and the angle, as the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76) describes for the Pen. The values run from the anchor being shaped to the end of the handle the drag shapes: the outgoing handle of a new or added anchor or of the last anchor, and the incoming handle of the first anchor when the drag closes the path. Shift gives the constrained handle, Space moves the anchor with its handle, and the readout starts past the 3-pixel drag threshold and ends when the button comes up, the press is dropped or the tool changes. These details are VectorCraft's own rules. Tests: the `info_readout_*` tests in `pen::tests`; scores and estimates unchanged. + - **Pen rubber band after a smooth anchor:** the preview segment to the pointer is the curve a click there adds, leaving the last anchor along its outgoing handle and arriving at the new corner anchor without a handle, so the segment keeps its shape when the anchor is placed, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes. Before, the preview was a different curve, and the segment changed shape at the click (#8296, in part; `pen::tests::rubber_band_is_the_segment_a_click_adds`); scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. @@ -1331,7 +1349,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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). + 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. Shear takes an angle from -359° to 359° and shears by its tangent, so 120° slants as -60°; an angle outside that range, and ±90° and ±270° (VectorCraft's own rule), return an error ([shear objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `shear_angles_slant_by_their_tangent`, `shear_rejects_angles_with_no_shear_or_out_of_range`). 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). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). Shear's axis is Horizontal, Vertical or Angle: the Shear dialog's Axis Angle field, and a numeric `axis` on `object.shear`, set a line on the page from -359° to 359° that the art slides along, apart from the shear angle; an axis angle outside that range is an error and nothing changes ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) describes this angled axis and its range; counter-clockwise from horizontal and the field's 0° start are our choices). Tests: `shear_along_an_axis_at_an_angle`, `reflect_and_shear_reject_unknown_axes_without_changing_state` and `shear_takes_an_axis_angle`. @@ -1431,7 +1449,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). `path.blob` rejects an Angle outside −180° to 180°, a Roundness outside 0% to 100% and a Fidelity outside 0.01 to 100 pt with an error and leaves the document unchanged; a key left out or null takes its default (0°, 100% and no fitting). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). -- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. A guide's row has its own eye and lock, which hide or lock that guide alone in one undo step and take part in a drag down either column ([help page](https://helpx.adobe.com/in_hi/tutorial-builder/user-guide/illustrator-tutorial-builder/-ai--examples-of-common-coach-marks.html) lists a Guide among the Layers panel's items); a hidden guide is not drawn and does not snap, a locked one is drawn and snaps but can't be selected, moved or deleted, and its own state is kept through save and reopen and while its layer is hidden or locked (`layer.setProps` on its `guide.list` id). Object › Lock › Selection and Object › Hide › Selection lock or hide a selected guide with the selected art, and Unlock All and Show All unlock or show such guides and select them ([help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) for Lock and Hide Selection). A guide row dropped on the panel's trash deletes its guide, the trash deletes a guide its row selected, and after a click on a guide row Delete deletes the guide rather than the rows highlighted before ([help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) for deleting a selected guide). A plain click on another row lets go of a guide its row selected, keeping the selected art, as a plain click on a row picks that row alone; a Ctrl/Cmd or Shift click keeps it (#7340, `panels::layers` test `a_plain_row_click_lets_go_of_the_selected_guide`). Not done: guides stacked among the art of their layer (they are listed above it). Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. +- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. A guide's row has its own eye and lock, which hide or lock that guide alone in one undo step and take part in a drag down either column ([help page](https://helpx.adobe.com/in_hi/tutorial-builder/user-guide/illustrator-tutorial-builder/-ai--examples-of-common-coach-marks.html) lists a Guide among the Layers panel's items); a hidden guide is not drawn and does not snap, a locked one is drawn and snaps but can't be selected, moved or deleted, and its own state is kept through save and reopen and while its layer is hidden or locked (`layer.setProps` on its `guide.list` id). Object › Lock › Selection and Object › Hide › Selection lock or hide a selected guide with the selected art, and Unlock All and Show All unlock or show such guides and select them ([help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) for Lock and Hide Selection). A guide row dropped on the panel's trash deletes its guide, the trash deletes a guide its row selected, and after a click on a guide row Delete deletes the guide rather than the rows highlighted before ([help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html) for deleting a selected guide). A plain click on another row lets go of a guide its row selected, keeping the selected art, as a plain click on a row picks that row alone; a Ctrl/Cmd or Shift click keeps it (#7340, `panels::layers` test `a_plain_row_click_lets_go_of_the_selected_guide`). Not done: guides stacked among the art of their layer (they are listed above it). Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). Preferences › Guides & Grid › Lock Guides by Default locks guides when the app starts; it is off by default, and new guides can still be dragged out of a ruler while guides are locked. The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score. While Lock Guides is on or the guides are hidden, a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out the paths made into guides inside groups and compound paths, as clicks do, so a locked guide does not select its group; an enclosing marquee measures a group without them (#8538; `a_marquee_skips_guide_paths_in_groups_while_guides_are_locked` in `crates/doc/src/hit/tests.rs`, `a_marquee_over_a_locked_guide_in_a_group_selects_nothing` in `crates/tools/src/select/tests.rs`). - **Releasing ruler guides:** View › Guides › Release Guides turns the selected ruler guides into paths with no fill or stroke. An artboard guide becomes a line across its artboard, and a canvas guide becomes a line across the artboards (`view.guides.release {index?, ids?}`). A Cmd/Ctrl+Shift double-click with the Selection, Direct Selection or Group Selection tool releases the ruler guide or guide path under the pointer. - **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (layers dropped in the empty space under the last row go below the bottom layer, #2260; dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Collect for Export (As Single Asset, As Multiple Assets), Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Right-clicking a layer, sublayer, group or object row offers Collect for Export for that row, or for every highlighted row when it is one of them; guide and blend spine rows have no context menu. Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638). With Paste Remembers Layers on, art copied from a sublayer pastes back into that sublayer, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=223) describes art going back to the layer it was copied from: in the same document while the sublayer is still there, two sublayers of the same name in different layers kept apart; in another document by the names of the sublayer and the layers around it. These rules are VectorCraft's own: a missing sublayer is made inside its layer (a missing layer on top, with the sublayer inside it), in the paste's one undo step; of layers with the same names, the topmost chain that matches the most names wins, a shown and unlocked one first; a matched layer that is hidden or locked, or inside one that is, refuses the paste, and nothing is pasted. @@ -1447,6 +1465,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches without one, and among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and results without typos keep their order (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `misspelled_words_find_the_command`). + A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). + A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). + Each Command Palette row starts with an icon for its kind (a tool's own icon, or one for a panel, an effect, a filter plug-in or a command) and shows where the result lives after its label, in smaller dim text: the menu path of the menu bar item that runs it, with that item's label when it differs from the result's ("File › Exit" for Quit VectorCraft), and "No menu item" for a command no item runs. A panel's row shows "Window". A row with a home shows its label without the menu path in front of it. A path that keeps two results' names apart stays in the label, unless the row's home shows the same path; a tool's row drops the "Tools" in front of its name. A tool's row names the toolbar it is on: "Toolbar" for its button on the Tools panel, or the name of a toolbar made with New Toolbar, followed by ", in the group" when the tool is hidden in the group of a slot whose button shows another tool ("Toolbar, in the Direct Selection Tool group" for the Group Selection Tool), and "All Tools" when no toolbar holds it. A toolbar shown now comes first (the Tools panel, then the toolbars made with New Toolbar), then a hidden Tools panel, then hidden toolbars made with New Toolbar; toolbars count as hidden in Presentation Mode and while Tab hides the panels. The Learn command (`window.learn`), which Window › Learn runs, takes the Window menu as its home, so a search reads its menu path like any other result's, and among results that tie on everything else it ranks as a command of the menu bar, before panels and after tools. The home is cut short with "…" before the label, and a label too long for the row keeps the id it shows after its name unless the id alone is wider than the row. A cut row shows all its text while the pointer rests on it, and screen readers read the kind, the label, the home and the shortcut. The row height is unchanged (`palette` tests `rows_show_where_each_result_lives`, `no_two_rows_read_alike`, `a_tool_row_names_its_toolbar_slot`, `a_narrow_row_cuts_the_home_first_and_keeps_the_id`, `screen_readers_hear_the_kind_and_home`, `catalogs_translate_the_kind_and_home_words`). + While the Command Palette is open, the highlighted result points to where it lives, in the same frame the arrow keys or the pointer move the highlight. A result with an item of the in-window menu bar has that menu's title outlined, with the item's whole path in a box under it ("Effect › Stylize › Round Corners…"); a panel points at the Window menu. A tool has its slot's button outlined on the toolbar the row names, or its own button on a strip torn off its group, with a box on the canvas side of the toolbar that names the tool, or says "In the Direct Selection Tool group: press and hold to open it" for a tool hidden in a group; screen readers hear that sentence with the search field's description. The box stays inside the window and off the button and the palette's popup: beside a button, its text wraps to up to three rows to fit before the popup or the window's edge, and where it still does not fit, the footer shows the text and only the outline is drawn; when the popup covers the control, nothing is drawn and the footer names the home. Nothing opens or shows: no menu, flyout, toolbar or All Tools drawer, and the chosen tool stays. With the system's menu bar, the footer reads "In the menu bar:" and the path instead; when no control in view shows the home (Presentation Mode, toolbars hidden by Window › Tools or Tab, a button scrolled out of view or under a floating panel or another toolbar) the footer names the home followed by "not shown now", and a command with no menu item reads "No menu item" with its shortcut. The menu bar and the toolbars note where they drew their controls only while the palette is open, and the palette uses only what this pass drew in its own window (`palette` tests `the_highlighted_result_outlines_its_menu_title`, `with_a_native_menu_bar_the_footer_names_the_path`, `a_tool_result_outlines_its_toolbar_slot`, `a_tool_on_a_toolbar_made_with_new_toolbar_is_outlined_there`, `a_strip_torn_off_the_tools_panel_is_pointed_at`, `a_box_beside_a_button_wraps_to_fit_beside_the_popup`, `the_box_keeps_off_its_button`, `the_callout_stays_off_the_palette`, `the_callout_keeps_off_a_popup_that_grew_in_the_same_pass`, `a_home_out_of_view_is_named_in_the_footer`, `the_pass_that_opens_the_palette_names_no_home_as_hidden`, `the_callout_follows_the_pointer`, `the_callout_follows_the_highlight_and_reveals_nothing`, `only_a_control_in_view_in_this_pass_is_pointed_at`, `a_control_under_a_window_is_not_pointed_at`, `the_noted_controls_hold_one_pass_per_viewport`, `catalogs_translate_the_callout_words`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. 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 these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. @@ -1589,6 +1612,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: Escape and the replacement search:** Escape with the Replace With Font From or Find In list open closes only the list. The dialog stays open with its choices and its search, also while Escape is held down, and the next press of Escape closes it. Done, Enter, Escape, and Find in Folder… once the Missing Fonts dialog opens, each forget the replacement search, so the next Find Font starts with an empty one; with no folder picked, Find Font stays open with its search. This is VectorCraft's own rule: a dropdown or popover open in a dialog closes before the dialog. Tests: `crates/ui-egui/src/find_font.rs`. - **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`. +- **Find Font works out the document's fonts once per version:** while Type › Find Font… is open, its Document list (`text.fonts`) and whether it shows Find in Folder… (the document misses a font) are worked out once for each version of the document's content and of the available fonts, and later frames reuse them. The list and the button are the same as before; an edit, an undo, another document in front, entering or leaving pattern editing, a composite font defined or taken out, and fonts added or scanned again give them anew. With 2,000 point-type objects of 50 characters each, set in five installed faces and a missing family, working them out took a median 1.53 ms of thread CPU time per frame in a release build on Linux; the first frame after a change still takes about as long, and later frames take about 10 ns. With 20 such objects it took 58 µs per frame. Tests: `find_font::tests::the_font_list_is_worked_out_once_per_document_version`, `an_edit_works_the_font_list_out_again`, `other_available_fonts_work_the_font_list_out_again`, `the_font_list_follows_the_document_in_front`; the timing probe is `find_font::tests::find_font_list_timing`. - **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). 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). It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. 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). @@ -1831,6 +1855,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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`). + The "?" on the Fill and Stroke proxies finds a few selected objects along their cached places in the document instead of walking every object; a large selection takes one walk, as before. The proxies show the same paints and question marks as before, also for an id that a damaged file repeats. On a document of 50,000 rectangles in 500 groups on 5 layers with one object selected, the check takes under 5 µs of CPU time instead of a median of 995 µs in a release build on Linux, so the gain shows on large documents (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Segments dragged onto the grid (#3835):** with View › Snap to Grid (or Snap to Pixel) on, a straight segment dragged with Direct Selection or Group Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis as a moved object's does (Shift keeps the move on its line), instead of the point it was pressed at landing on an intersection and leaving both anchors off the grid; a dragged anchor still lands on an intersection itself, and drawn points and resize handles already snapped (`direct::tests::a_dragged_segment_lands_its_anchors_on_the_grid`). - **Spinner arrows in the shadow and glow dialogs (#5367, #5368):** Drop Shadow's Opacity, X Offset, Y Offset, Blur and Darkness and the Outer and Inner Glow's Opacity and Blur have up and down arrows beside the field, as the other number fields with arrows do: a click steps by one (a unit for distances; Shift ×10, Ctrl/Cmd ÷10), holding repeats, Opacity and Darkness stop at 0 and 100 % and Blur at 0 (`dialogs::effect` test `drop_shadow_and_outer_glow_fields_have_spinner_arrows`). @@ -1916,7 +1941,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. - Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds. + Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). 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`). EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). @@ -1942,6 +1967,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named ` copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`). The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`). + A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -1981,7 +2007,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font, and Print and Print Preview warn about the type that prints in it; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite and, for those only GDI lists, through GDI (#1258), and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`). 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). A variable font's type gets one slider and field per variation axis under the Character panel's Variable Font button, each named as the font names the axis (Weight, Width), so the type can be set between or past its named instances: the settings stay with the characters (`CharStyle::font_axes`, `text.setFormat {fontAxes}` and `text.setRangeStyle {fontAxes}`, clamped to each axis's range; `text.fontList {family, style}` lists the axes), and layout, outlines, the substituted-glyph highlight and PDF and SVG export (`font-variation-settings`, embedded fonts) use the font instanced at them. Another font or style clears them; legacy `.ai` export writes the style and warns that they are left out. The font menu's Font Technology › Variable (under the kind filter, as [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) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`. - The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. + The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, as does type in the art of a stored scatter brush (art and pattern brushes leave type out when they bend their art, so their type does not count), styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs`, `font_menu::tests::the_document_filter_counts_type_in_scatter_brushes`, `font_menu::tests::the_document_filter_follows_a_scatter_brushs_edits_and_undo` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`. While the samples are shown, the font menu's row under the filters sets the sample size to Small, Medium or Large from inside the menu, as the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) and the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485) describe the sample size control; with Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: the row sits under the filters and sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, the Composite Fonts and Dimension dialogs' included, and the open list stays on the rows it showed; the current size is selected and a click on it changes nothing; screen readers find the three sizes as radio buttons in a group named Font Preview Size; a saved value that is none of the three sizes shows Medium and a click replaces it; the change adds no undo step and leaves a font previewed on the selected type in place. Measured by `font_menu::tests::the_preview_size_row_asks_for_the_size_clicked`, `font_menu::tests::a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview`, `font_menu::tests::the_preview_size_row_is_a_radio_group_showing_the_size` and `font_menu::tests::a_new_preview_size_keeps_the_list_on_its_rows`. The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR= cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). @@ -2251,6 +2277,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). - EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines). + - EPS import: `token` on a string, `search` and `anchorsearch` read their strings in place instead of copying the rest of the string on each call, with the same results, errors and operation count as before. Walking a 512 KiB string by what each call leaves takes 16 ms instead of 518 ms with `token` and 1.0 ms instead of 27 ms with `search`, and a 64 KiB string 2.2 ms instead of 10 ms with `token`; on a 4 KiB string the difference is under 0.1 ms (release build on Linux under load from other builds, median of 7 alternating runs, `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`). - **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). - **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac). - **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875). @@ -2419,6 +2446,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. - **A disabled plug-in whose update stays in the store is turned on:** when `plugin.install` writes a module that lists permissions to the `Plug-ins` folder, its grant can't be written, and the folder can't be returned to the old module (or, on a first install, the new module can't be removed), the folder holds the new module, so a disabled plug-in is turned on, by id and by stored file, as for any install the folder holds. The old grant, or none, doesn't cover the new module, so the next start skips it until it is approved. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -2751,7 +2779,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting ## Path Precision Tools add-on: Common Tangents (2026-11-15) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. Since 2026-11-18 one of the two may be a point (a path of one anchor): the lines run from the point to where they touch the path, two from a point outside it, one at a point on its outline or less than the touching tolerance from it (centered on the point, or covering the straight side it lies on), and none from a point inside, with a message; the centerline runs from the point to the path's center, and every Tangents choice gives the same lines. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, a point outside a turned ellipse, on a circle, inside it, beside a square and at its corner, on a turned outline, within the touching tolerance, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` and `common_tangents_on_a_point_gives_the_same_lines_for_every_choice` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) @@ -2910,6 +2938,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | +| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | @@ -2931,6 +2961,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | | 2026-11-12 | minor | Glyphs review (#6084): Entire Font uses the selection's version and variable axes for previews and alternate applicability. The default cell can reset an unlisted glyph choice when GSUB lists no alternates. Encoded Latin and other ordinary characters insert unchanged even if their glyph also has Arabic positional provenance; Arabic presentation forms retain base-letter insertion. Remove a redundant charmap scan from unlisted-glyph checks. Scores and estimates unchanged. | | 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | +| 2026-11-12 | minor | Blend redraw (#5179): renderer bounds include spine-placed keys and steps. Original straight and curved Replace Spine, move and Undo CPU regressions pass; scores and estimates unchanged. | | 2026-11-09 | minor | Glyphs review (#6084): positional alternates with no supported feature are accepted as glyph choices in both panel views; Entire Font's unlisted-glyph and name-ownership behavior is retained. OpenType style options keep only a valid last on-value when enabling a set. Contradictory old glyph-choice evidence corrected; scores and estimates unchanged. | | 2026-11-07 | minor | Type core: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to the selected letter alone, so an Arabic word stays joined (`salt=2`; the style commands take `tag=N`), and Show › Entire Font lists the glyphs no character maps (#5514; [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html)); evidence added; scores unchanged. | | 2026-11-12 | minor | UI chrome: a numeric-field 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 hours unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e44a28165c..d218ec4e3d 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-16 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #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). > @@ -10,6 +10,8 @@ > > Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). +> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. + > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. ## Feature submission evidence @@ -195,6 +197,7 @@ tools, never checked side by side) isn't captured row by row. | Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` | | Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | +| Blend Replace Spine, move and Undo redraw (#5179) | CPU regression-tested | Renderer damage bounds include keys and steps rotated along a curved spine. Both original straight and curved CPU regressions pass, checking full-frame agreement and that every changed pixel lies inside the advertised redraw area. | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | @@ -273,7 +276,7 @@ tools, never checked side by side) isn't captured row by row. | Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | -| Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete); a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701 | +| Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete), in groups as well: a marquee leaves them out, so it does not take their group, and they still move with their group; a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701; #8538 | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | | Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | | Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | @@ -394,6 +397,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po ## Panels, Control bar, Properties, context menus +- [x] **Production Preflight (VectorCraft addition):** Window panel with PDF, Print and Screen targets, a minimum PPI and all/active-artboard scope; four check summaries, clickable findings, Find Font/Relink/Update actions, automatic revision/timed rechecks and explicit incomplete coverage. See [production-preflight.md](production-preflight.md). + - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. | Interaction | Status | Evidence | @@ -457,7 +462,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; eleven built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -579,6 +584,8 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | +| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. | | 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. | @@ -589,6 +596,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | | 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | +| 2026-11-12 | minor | Blend redraw (#5179): renderer bounds include spine-placed keys and steps. Original straight and curved Replace Spine, move and Undo CPU regressions pass; scores and estimates unchanged. | | 2026-11-11 | minor | Ruler origin: the corner drag snaps as a drawn point does, onto the art's and the artboards' anchors, centres, edges and paths, and with Snap to Point along the ruler guides; scores and estimates unchanged | | 2026-11-11 | minor | macOS canvas cursor delivery (#2292): while the host owns the cursor it sets it again on every pass, so the tool's cursor stays after the pointer moves (#6362); `mac_cursor` ownership test updated; scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. |