mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 19:11:26 +00:00
Merge remote-tracking branch 'upstream/main' into fix-8543-pdf-tj-fill-stroke
# Conflicts: # docs/roadmap.md # docs/target-app-parity.md
This commit is contained in:
@@ -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<crate::Arrowhead> {
|
||||
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")]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
@@ -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);
|
||||
|
||||
@@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], 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<UsedFont, BTreeSet<NodeId>>,
|
||||
pub overflow: BTreeSet<NodeId>,
|
||||
pub images: BTreeMap<NodeId, NodeId>,
|
||||
}
|
||||
|
||||
pub(super) fn preflight_type(d: &Document, layers: &[Arc<Node>], 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<String>,
|
||||
patterns: BTreeSet<String>,
|
||||
preflight: Option<PreflightType>,
|
||||
owner: Option<NodeId>,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -369,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Option<Affine>, 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<f64, String> {
|
||||
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<Value> {
|
||||
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") {
|
||||
|
||||
@@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
const C: &str = "image.info";
|
||||
let st = s.doc()?;
|
||||
@@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
"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(),
|
||||
}))
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
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::<Vec<_>>();
|
||||
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::<Vec<_>>(), "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()) })
|
||||
}
|
||||
@@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result<PreflightContext> {
|
||||
let settings =
|
||||
json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::<Vec<_>>().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<Rect> {
|
||||
pv.sheets
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<u8> {
|
||||
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()
|
||||
}
|
||||
@@ -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::<Value>(&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();
|
||||
|
||||
@@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
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"}},
|
||||
|
||||
@@ -302,6 +302,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
// 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<Value, String>
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -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<String, Value>, 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<String, Value>, 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<String, Value>, 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<egui::Rect>) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 Последни команди
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 Πρόσφατες εντολές
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 તાજેતરના આદેશો
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -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 हाल के आदेश
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2538 and column 5.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 最近使ったコマンド
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 ბოლოდროინდელი ბრძანებები
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 최근 명령
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 Недавние команды
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 Нещодавні команди
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 最近使用的命令
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -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 最近使用的指令
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -707,6 +707,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> {
|
||||
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"),
|
||||
|
||||
+384
-19
@@ -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<Option<String>> =
|
||||
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<Entry> {
|
||||
@@ -374,7 +398,16 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec<Entry> {
|
||||
}
|
||||
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 <tool> 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<egui::Galley>, Option<Arc<egui::Galley>>, 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<String> {
|
||||
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<String> = 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<String> = 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::<String>();
|
||||
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<String> = 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()));
|
||||
}
|
||||
|
||||
@@ -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<Box<str>, 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<String>) -> HashMap<Box<str>, u16> {
|
||||
let mut out: HashMap<Box<str>, 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<String> {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
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<usize> = vec![0; b.len() + 1];
|
||||
let mut last: Vec<usize> = (0..=b.len()).collect();
|
||||
let mut row: Vec<usize> = 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<u8>) {
|
||||
@@ -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::<Vec<_>>().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<Item = &str> {
|
||||
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<String>]) -> 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<String>], params: &[&str], search_row: impl Fn(&str) -> Option<String>) -> 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::<Posting>()
|
||||
+ self.initials_text.capacity()
|
||||
+ self.initials.capacity() * std::mem::size_of::<(u32, u16)>()
|
||||
+ self.synonyms.capacity() * (std::mem::size_of::<(Box<str>, u16)>() + 1)
|
||||
+ self.synonyms.keys().map(|w| w.len()).sum::<usize>()
|
||||
}
|
||||
|
||||
/// 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<u8> {
|
||||
let mut out = vec![NONE; n];
|
||||
let mut mark = |postings: &[Posting], grade: &dyn Fn(u8) -> Option<u8>| {
|
||||
@@ -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<usize> {
|
||||
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<usize> = 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<usize> {
|
||||
let Some(bound) = typo_bound(word) else { return vec![] };
|
||||
let word: Vec<char> = word.chars().collect();
|
||||
let mut term: Vec<char> = 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<u32> {
|
||||
let query = normalize(query);
|
||||
if query.is_empty() {
|
||||
@@ -399,8 +673,39 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec<u32> {
|
||||
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<usize> = tokens.iter().map(|t| (t.as_ptr() as usize).saturating_sub(head.as_ptr() as usize)).collect();
|
||||
let n = entries.len();
|
||||
let indexed: Vec<Vec<u8>> = tokens.iter().map(|t| index.grades(t, n)).collect();
|
||||
let mut indexed: Vec<Vec<u8>> = Vec::with_capacity(tokens.len());
|
||||
let mut typos: Vec<Vec<usize>> = Vec::with_capacity(tokens.len());
|
||||
let mut meanings: Vec<Vec<usize>> = 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<u32> {
|
||||
// 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<String, (String, &'static str)
|
||||
match it {
|
||||
menus::Item::Cmd(label, id, p) if !skip.contains(id) => {
|
||||
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<Entry>) -> Catalog {
|
||||
let index = Index::build(&entries, &[]);
|
||||
described(entries, &[])
|
||||
}
|
||||
|
||||
/// `entries` with their index, the params text of each in `params`.
|
||||
fn described(entries: Vec<Entry>, 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::<Vec<_>>(), &b.chars().collect::<Vec<_>>(), 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<Entry> = 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::<Vec<_>>();
|
||||
let spelled_right: Vec<String> = 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<usize> = 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 {
|
||||
|
||||
@@ -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<Item = (String, bool)> + '_ {
|
||||
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<String> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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<usize>, u64)>,
|
||||
at: f64,
|
||||
report: Value,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
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::<Vec<_>>();
|
||||
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;
|
||||
@@ -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<egui::Event>) -> 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::<Vec<_>>().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();
|
||||
}
|
||||
@@ -416,7 +416,7 @@ pub(super) fn arrow_doc(mut a: Option<Arrowhead>, 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);
|
||||
}
|
||||
|
||||
@@ -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<Item = (usize, char, usize)> + '_ {
|
||||
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<Entry> {
|
||||
entries().iter().find(|e| e.key == key).cloned()
|
||||
}
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -50,11 +50,23 @@ pub fn dropdown_icon_names(
|
||||
width: f32,
|
||||
icon_size: f32,
|
||||
icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool),
|
||||
) -> Option<usize> {
|
||||
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<usize>,
|
||||
options: &[&str],
|
||||
width: f32,
|
||||
icon_size: Vec2,
|
||||
icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool),
|
||||
) -> Option<usize> {
|
||||
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(),
|
||||
|
||||
+4
-1
File diff suppressed because one or more lines are too long
+27
-6
@@ -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. |
|
||||
|
||||
@@ -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. |
|
||||
+3
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4
-1
@@ -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. |
|
||||
|
||||
Reference in New Issue
Block a user