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/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/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/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/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/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/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/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/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 94c54dea4f..f864877025 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(); 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/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 56b2f95944..a8d6cc86e6 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1636,6 +1636,33 @@ 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 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..d730f8deaf 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 centre; `copy` transforms a copy. A scale, reflect or shear its command refuses 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..619af2e12e 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -302,6 +302,24 @@ 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. + 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"))?; + } + let reflect = a.get("reflect").and_then(Value::as_str); + 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"))?; + } 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)); @@ -322,17 +340,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/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/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 d94e1c7d24..59dc587ee7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3359,6 +3359,9 @@ 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} @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 Последни команди diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 39ac7db214..8c1e89f56c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4480,6 +4480,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ffd2ff9978..ae39014e79 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4302,6 +4302,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ee98b35833..2ebf9b2358 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4588,6 +4588,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 76b8454d8f..d5d909f8df 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7012,6 +7012,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 354dc28ccd..501406ef1e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3437,6 +3437,11 @@ 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}“ + 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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index dbfb0580d9..26202d14fa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4178,6 +4178,9 @@ 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} @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 Πρόσφατες εντολές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 320212f9f6..bee8f3bfe7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3472,6 +3472,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b0e15588b0..ec15ca6a99 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4503,6 +4503,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1a0b4f68fd..c8b973b692 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3460,6 +3460,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 9f3ca59342..614baf3b2a 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3569,6 +3569,12 @@ 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} જૂથમાં + 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 તાજેતરના આદેશો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e15913b6ab..98866a4a85 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4654,6 +4654,9 @@ 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} समूह में @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 हाल के आदेश diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e20bc88c72..4fb8eb2a15 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4095,6 +4095,9 @@ 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 @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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c69622c2c0..1cf9cd9a10 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4228,6 +4228,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index bb32e731c3..e0c426bd1c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3522,6 +3522,11 @@ 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} + 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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5f7072f081..522dfd3573 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3407,6 +3407,9 @@ 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} のグループ内 @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 最近使ったコマンド diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 08a3f2376b..b84d5aa71b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6299,6 +6299,9 @@ 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} @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 ბოლოდროინდელი ბრძანებები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7119fe03f7..61bda0cfa7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3396,6 +3396,11 @@ 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} 그룹 + 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 최근 명령 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4d22a5fe70..14cc29d30f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4885,6 +4885,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0b4ef470dd..aeec776910 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4431,6 +4431,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e86afd1868..78012c35eb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2924,6 +2924,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 864a0fb8db..74ea8a881b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3504,6 +3504,9 @@ 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}» @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 Недавние команды diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7d63da5059..ed601312a4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3384,6 +3384,9 @@ 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} @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 diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index be56dca076..1ef955c627 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -804,6 +804,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 0ad63d9d7c..99be17c885 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3262,6 +3262,9 @@ 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 @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 diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 748947c239..d6f50c5ebc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3514,6 +3514,11 @@ 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}» + 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 Нещодавні команди diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 87ca6cd62a..bb00f747b8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3860,6 +3860,11 @@ 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} + 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 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7908b3df6e..617b9ac1e8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3339,6 +3339,9 @@ 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} 组中 @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 最近使用的命令 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e284447f7d..ebcc33d25f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4717,6 +4717,11 @@ 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} 群組中 + 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 最近使用的指令 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/palette.rs b/crates/ui-egui/src/palette.rs index 6122e7357b..9832567689 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 @@ -286,6 +287,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. @@ -338,10 +345,27 @@ 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); + // 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 +398,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 +478,87 @@ 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), crate::i18n::tr(lang, e.menu_item)), + 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; "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)); + let main = main.map(|slot| place(tl!("Toolbar"), 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(); + 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}") } } /// The line under the results: how many results matched, how many of them the list holds when it @@ -502,6 +612,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; @@ -740,7 +885,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { 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)]); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } if n > 0 { @@ -765,16 +911,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()); @@ -1934,6 +2093,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 +2207,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 +2282,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 +2375,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 +2397,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 +2647,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 +2660,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 +3145,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,7 +3233,7 @@ 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())); } 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/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/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/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/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/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/docs/gaps.md b/docs/gaps.md index 304535dacb..509b91cdae 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (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) +> **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. @@ -478,6 +478,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. @@ -910,6 +912,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. | diff --git a/docs/mcp.md b/docs/mcp.md index d55d565991..d06b64ff54 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). @@ -724,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. | | `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. | @@ -6774,8 +6774,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. @@ -7294,8 +7295,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 @@ -9217,6 +9222,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 @@ -14354,6 +14374,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/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 54fb031266..0302eba0e0 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-18 · **Change:** minor (PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF 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). > @@ -164,7 +164,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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 | | 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 for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; 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 for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; 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 | @@ -217,6 +217,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| | 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; 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. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 30cace80d2..a284beb00d 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-18 · **Change:** minor (PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF 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). > @@ -284,7 +284,7 @@ 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 | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | @@ -544,7 +544,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | 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 | | 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 for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; scores and estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; 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 | @@ -592,6 +592,8 @@ 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`). @@ -638,6 +640,7 @@ since 2026-10-01. **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 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. @@ -1335,7 +1338,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`. @@ -1451,6 +1454,10 @@ 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`). `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. @@ -2919,6 +2926,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 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 | 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. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e44a28165c..349e0b8bb7 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 (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). > @@ -394,6 +394,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 | @@ -579,6 +581,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 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-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. |