From ebe718808be566e9a2e08d6f4f4e3b8cf1603d21 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:56:04 +0430 Subject: [PATCH 01/71] Fix #4462: SVG export can write width and height in mm, cm or in SVG Options gets a units choice (px, pt, mm, cm, in) for the width and height an export writes; px stays the default and writes bare numbers as before, the viewBox stays in points. An unknown unit is an error. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/svg.rs | 6 ++++ crates/engine/src/cmd/fileio/tests_svg.rs | 26 ++++++++++++++ crates/svg/src/export.rs | 4 ++- crates/svg/src/lib.rs | 41 +++++++++++++++++++++++ crates/svg/tests/it/roundtrip.rs | 17 +++++++++- crates/ui-egui/src/dialogs/svg_options.rs | 6 ++-- docs/control-protocol.md | 2 +- docs/file-format-parity.md | 5 +-- docs/gaps.md | 6 +++- docs/mcp.md | 2 +- docs/target-app-parity.md | 7 ++-- docs/ui-parity.md | 3 +- 13 files changed, 113 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index f269f0fc0f..60c0f72ee1 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index a11e4a4e8f..ba843ab557 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -48,6 +48,12 @@ pub const OPTIONS: &[FormatOption] = &[ FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" }, FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" }, + FormatOption { + name: "units", + ty: "string", + default: "\"px\"", + description: "the unit of width and height: px (bare numbers, one per point) | pt | mm | cm | in (the viewBox stays in points; not with responsive)", + }, FormatOption { name: "preserveEditing", ty: "boolean", diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 73ee604a98..ed5cbc707b 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -83,6 +83,8 @@ fn junk_options_are_rejected() { json!({"svg": "css"}), json!({"images": "inline"}), json!({"useArtboards": "yes"}), + json!({"units": "furlong"}), + json!({"units": 7}), ] { let mut q = p.clone(); q["format"] = json!("svg"); @@ -92,6 +94,30 @@ fn junk_options_are_rejected() { assert!(s.execute("document.export", &json!({"format": "png", "styling": "fancy"})).is_ok()); } +/// #4462: width and height carry the chosen unit (the document is 200 × 100 pt, the viewBox stays +/// in points), px is today's bare numbers, and Responsive leaves the size out whatever the unit. +#[test] +fn svg_export_writes_width_height_with_the_requested_unit() { + let mut s = session(1); + let plain = svg(&mut s, json!({})); + assert!(plain.contains(" width=\"200\" height=\"100\" viewBox=\"0 0 200 100\""), "{plain}"); + assert_eq!(svg(&mut s, json!({"units": "px"})), plain, "px is the default, byte for byte"); + for (unit, size) in [ + ("mm", "width=\"70.556mm\" height=\"35.278mm\""), + ("cm", "width=\"7.056cm\" height=\"3.528cm\""), + ("in", "width=\"2.778in\" height=\"1.389in\""), + ("pt", "width=\"200pt\" height=\"100pt\""), + ] { + for p in [json!({"units": unit}), json!({"svg": {"units": unit}})] { + let out = svg(&mut s, p); + assert!(out.contains(&format!(" {size} viewBox=\"0 0 200 100\"")), "{unit}:\n{out}"); + } + } + let out = svg(&mut s, json!({"units": "mm", "responsive": true})); + assert!(!out.contains("mm\"") && !out.contains("height=\"100\" viewBox") && out.contains("viewBox=\"0 0 200 100\""), "{out}"); + assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("width=\"70.6mm\" height=\"35.3mm\"")); +} + #[test] fn several_artboards_write_one_file_each() { let mut s = session(3); diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 13c4268472..2b91bf7b8c 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -162,7 +162,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: out.push_str(" version=\"1.2\" baseProfile=\"tiny\""); } if !opts.responsive { - out.push_str(&format!(" width=\"{ww}\" height=\"{hh}\"")); + // The viewBox stays in user units (points); the unit only scales the drawn size. + let (width, height) = (opts.units.length(rect.width(), opts.decimals), opts.units.length(rect.height(), opts.decimals)); + out.push_str(&format!(" width=\"{width}\" height=\"{height}\"")); } out.push_str(&format!(" viewBox=\"0 0 {ww} {hh}\">{nl}")); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ccc154a383..2ab97856f8 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -177,6 +177,43 @@ impl Encoding { } } +/// The unit of the `width` and `height` an export writes (SVG Options → Units, off Responsive). +/// The `viewBox` stays in user units (points) whatever is chosen. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SizeUnit { + /// Bare numbers, CSS pixels at one per point (72 per inch). + #[default] + #[serde(rename = "px")] + Px, + #[serde(rename = "pt")] + Pt, + #[serde(rename = "mm")] + Mm, + #[serde(rename = "cm")] + Cm, + #[serde(rename = "in")] + In, +} + +impl SizeUnit { + /// This unit's size in points, and the suffix a length in it carries (`px` is written bare). + fn per_point(self) -> (f64, &'static str) { + match self { + Self::Px => (1.0, ""), + Self::Pt => (1.0, "pt"), + Self::Mm => (25.4 / 72.0, "mm"), + Self::Cm => (2.54 / 72.0, "cm"), + Self::In => (1.0 / 72.0, "in"), + } + } + + /// `points` as a length in this unit, rounded to `decimals` places, e.g. `70.556mm`. + pub fn length(self, points: f64, decimals: u8) -> String { + let (scale, suffix) = self.per_point(); + format!("{}{suffix}", fmt_num(points * scale, decimals)) + } +} + /// The SVG profile written (SVG Options → SVG Profile). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum Profile { @@ -223,6 +260,9 @@ pub struct ExportOptions { pub minify: bool, /// Omit `width`/`height` so the SVG scales to its container. pub responsive: bool, + /// The unit `width` and `height` are written in (ignored when `responsive`). `px`, the + /// default, writes bare numbers. + pub units: SizeUnit, /// Fonts → Convert to Outlines: text becomes paths (portable, no font needed to view it). pub outline_text: bool, /// Embed the native document (passed to [`export_full`]) in `` so VectorCraft @@ -256,6 +296,7 @@ impl Default for ExportOptions { images: ImageMode::Embed, minify: false, responsive: false, + units: SizeUnit::Px, outline_text: false, preserve_editing: false, metadata: false, diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index fde9ff86f2..4ff2fd5bbe 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -6,7 +6,7 @@ use vectorcraft_doc::{ StrokeLayer, TextKind, TextObject, }; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, shapes}; -use vectorcraft_svg::{ExportOptions, ObjectIds, Styling, export, import, import_with_report}; +use vectorcraft_svg::{ExportOptions, ObjectIds, SizeUnit, Styling, export, import, import_with_report}; fn doc_with(nodes: Vec) -> Document { let mut d = Document::new(200.0, 200.0); @@ -547,6 +547,21 @@ fn options_decimals_minify_responsive_artboard() { assert!(!s.contains("id=\"Layer_1\"")); } +/// An SVG written with a physical width and height (#4462) reopens at the artboard it was written from. +#[test] +fn svg_in_physical_units_reopens_at_the_same_size() { + let mut d = Document::new(200.0, 100.0); + let n = rect_node(&mut d, Rect::new(10.0, 10.0, 60.0, 50.0), Appearance::default_art()); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + for units in [SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In, SizeUnit::Pt] { + let s = export(&d, &ExportOptions { units, ..Default::default() }); + let back = import(&s).unwrap_or_else(|e| panic!("{units:?}: {e}\n{s}")); + let r = back.artboards[0].rect; + assert!((r.width() - 200.0).abs() < 0.1 && (r.height() - 100.0).abs() < 0.1, "{units:?}: {r:?}\n{s}"); + } +} + #[test] fn unique_sanitized_ids() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index 14dc2d5a4f..5827da7d3c 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -1,5 +1,5 @@ //! SVG Options (Export As SVG, Save As / Save a Copy to .svg): profile, styling, fonts, images, -//! object ids, decimals, encoding, minify, responsive, embedded fonts, artboards (export) or +//! object ids, decimals, encoding, units, minify, responsive, embedded fonts, artboards (export) or //! editing data (save), and a read-only view of the code. OK remembers the choices for next time and runs the export or save command with //! them as `svg: {…}`. @@ -64,6 +64,7 @@ const IMAGES: [(&str, &str); 2] = [("embed", "Embed"), ("link", "Link")]; const OBJECT_IDS: [(&str, &str); 3] = [("layerNames", "Layer Names"), ("minimal", "Minimal"), ("unique", "Unique")]; const PROFILES: [(&str, &str); 2] = [("svg11", "SVG 1.1"), ("tiny12", "SVG Tiny 1.2")]; const ENCODINGS: [(&str, &str); 3] = [("utf8", "Unicode (UTF-8)"), ("utf16", "Unicode (UTF-16)"), ("latin1", "ISO 8859-1")]; +const UNITS: [(&str, &str); 5] = [("px", "Pixels"), ("pt", "Points"), ("mm", "Millimeters"), ("cm", "Centimeters"), ("in", "Inches")]; /// Dialog fields that are not SVG options. const UI_KEYS: [&str; 5] = ["mode", "path", "showCode", "allArtboards", "range"]; @@ -193,7 +194,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The SVG options: styling, fonts, images, object ids, decimals, minify, responsive, ``s +/// The SVG options: styling, fonts, images, object ids, decimals, units, minify, responsive, ``s /// and metadata. `screens` (Export for Screens' Format Settings) leaves out Images: a linked /// image is another file. pub(super) fn option_fields(ui: &mut egui::Ui, d: &mut Dialog, screens: bool) { @@ -216,6 +217,7 @@ pub(super) fn option_fields(ui: &mut egui::Ui, d: &mut Dialog, screens: bool) { } ui.end_row(); choice(ui, d, "encoding", tl!("Encoding:"), &ENCODINGS, None); + choice(ui, d, "units", tl!("Units:"), &UNITS, None); }); ui.add_space(6.0); ui.horizontal(|ui| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cdb7471df1..6b154fc1a0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -112,7 +112,7 @@ the two can still win that race. | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | | `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary). `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set | | `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab | -| SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | +| SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `units`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them | | `app.export` raster options | `{path?, format: png \| jpg \| webp, ppi?, width?, height?, background?, antiAlias?, interlaced?, quality?}` | `ppi` sets the pixel size (72 = one pixel per point) and is stored in PNG and JPEG files (WebP files store no resolution); `width` or `height` sets the size of each file in pixels instead (`width` wins), and PNG and JPEG files store the resolution that results; `background` is `transparent`, `white`, `black` or `"#rrggbb"`; `antiAlias` is `none`, `art` or `type` (text snapped to pixels); `interlaced` writes an Adam7 PNG. The PNG Options dialog (`pngOptions`; `jpgOptions` / `webpOptions` for the other raster formats) has the same fields: fill them with `ui.dialog.set` and press OK with `ui.dialog.confirm` | | `app.export` JPEG options | `{path?, format: jpg, quality?: 0–100, colorModel?: rgb \| cmyk \| gray, method?: baseline \| optimized \| progressive, scans?: 3–5, embedIcc?, imageMap?: none \| client \| server}` | `cmyk` writes ink amounts in the working CMYK space (CMYK colours keep their inks; RGB ones are separated with the colour settings); `embedIcc` (default true) embeds sRGB, the working CMYK profile or a grey profile, generated by the CMS; `imageMap` also writes `.html` (client-side ``) or `.map` (NCSA) beside the image for the objects with a URL and an Image Map shape (`attributes.set`), returned in `linked`. The `jpgOptions` dialog has these fields too (`quality` is shown 0–10; a CMYK document defaults to `cmyk`) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6f02703ca5..8d68f3bdc2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (native format: dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: native format: dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -125,7 +125,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | -| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | +| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | @@ -161,6 +161,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-01 | minor | Native format: a symbol's Symbol Type (`dynamic`) and a dynamic symbol instance's appearance changes to objects of its art (`symbol_overrides`) round-trip; both are left out when unset, so other documents save unchanged (#4938). `.ai` reading and writing of dynamic symbols remains. | | 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | diff --git a/docs/gaps.md b/docs/gaps.md index 8b707fd9f6..0eb22f0cdd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -317,6 +317,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall such stubs into one vertex (within 4× the sweep's tolerance up and down its frame and 1/16 of the 0.01 pt precision along it, bounded by each cluster's extent so a run of tiny level segments keeps its length); regression tests in `crates/pathops/src/planar.rs`. Estimate unchanged. +- **Done (2026-11-03):** SVG export writes `width` and `height` in the unit SVG Options › Units (`units`) names: `px` + (bare numbers, as before), `pt`, `mm`, `cm` or `in`, with the `viewBox` in points, so laser and plotter software reads + the physical size (#4462); an unknown unit is an error. Estimate unchanged. - **Missing:** SVG units reverting to points (#864). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) are done. @@ -732,6 +735,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | diff --git a/docs/mcp.md b/docs/mcp.md index 0ca4e32353..77c265492f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -581,7 +581,7 @@ colour group (one undo step). SVG Options: `export` to SVG takes them in `options`, flat or as `{"svg": {…}}`: `styling` (`presentation`, `style`, `entities`, `css`), `outlineText`, `images` (`embed`, or `link`: embedded images are written next to the SVG, or returned as `linked`), `objectIds` (`layerNames`, `minimal`, `unique`), `decimals` (1–7), `minify`, -`responsive`, `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG +`responsive`, `units` (`px`, `pt`, `mm`, `cm` or `in`: the unit `width` and `height` are written in, `px` meaning bare numbers as before; the `viewBox` stays in points; ignored with `responsive`), `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG reopens as the full document), `metadata` and `fewerTspans` (one `<tspan>` per line of type). Unknown keys inside `svg` are rejected; `run_command document.formats` lists every option with its default. `encoding` is `utf8`, `utf16` (big-endian after a byte order mark) or `latin1` (ISO 8859-1, other characters as `&#x…;` references); `document.serialize` still answers `text`, plus `dataBase64` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4370a3a0c..9b50f8cb24 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1108,8 +1108,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save as Template writes a PDF-compatible `.ait` as well as a `.vctemplate`, which stays the default: the save panel and the web build's Save as Template dialog list both, and New from Template opens the `.ait` as an untitled document with its layers and art (`file.saveAsTemplate {format: "ait"}`, or a path ending in `.ait`). Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. SVG Options › Units writes the export's `width` and `height` in px (bare numbers, the default), pt, mm, cm or in with the `viewBox` in points (#4462). + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. SVG Options › Units writes the export's `width` and `height` in px (bare numbers, the default), pt, mm, cm or in with the `viewBox` in points (#4462). In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -1565,6 +1565,7 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | | 2026-11-03 | minor | Find Font's replacement-source chooser offers Document, Recent and System (#5217); scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 26d3dd6790..d27331d90d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -418,6 +418,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | From 02169eb0abe8cb9e09d7d60e9b63fbd7d9c11c25 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:16:46 +0430 Subject: [PATCH 02/71] Fix #4462: tiny physical sizes never format as zero; Units is dimmed while Responsive is on (review) --- crates/svg/src/lib.rs | 28 +++++++++++++++++++++-- crates/ui-egui/src/dialogs/svg_options.rs | 4 +++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 2ab97856f8..407acef31d 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -207,10 +207,21 @@ impl SizeUnit { } } - /// `points` as a length in this unit, rounded to `decimals` places, e.g. `70.556mm`. + /// `points` as a length in this unit, rounded to `decimals` places, e.g. `70.556mm`. A + /// positive size never rounds to zero (a zero `width` disables rendering): in a unit with a + /// suffix it gets more places, up to 12, until a digit survives. `px` stays as [`fmt_num`] + /// writes it. pub fn length(self, points: f64, decimals: u8) -> String { + const MAX_PLACES: u8 = 12; let (scale, suffix) = self.per_point(); - format!("{}{suffix}", fmt_num(points * scale, decimals)) + let v = points * scale; + let mut places = decimals; + if !suffix.is_empty() && v.is_finite() && v > 0.0 { + while places < MAX_PLACES && fmt_num(v, places) == "0" { + places += 1; + } + } + format!("{}{suffix}", fmt_num(v, places)) } } @@ -711,6 +722,19 @@ mod tests { assert_eq!(fmt_num(100.0, 0), "100"); } + #[test] + fn tiny_physical_sizes_never_format_as_zero() { + // 3 pt is 0.0417 in: one place would write `0in`, and a zero width disables rendering. + assert_eq!(SizeUnit::In.length(3.0, 1), "0.04in"); + assert_eq!(SizeUnit::Mm.length(0.001, 1), "0.0004mm"); + // Nothing to widen when a digit survives, or when the size really is zero. + assert_eq!(SizeUnit::In.length(72.0, 1), "1in"); + assert_eq!(SizeUnit::In.length(0.0, 1), "0in"); + // `px` is written exactly as `fmt_num` does. + assert_eq!(SizeUnit::Px.length(3.0, 1), "3"); + assert_eq!(SizeUnit::Px.length(0.01, 1), "0"); + } + #[test] fn escaping() { assert_eq!(xml_escape("a<b>&\"'"), "a<b>&"'"); diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index 5827da7d3c..da5500dd1e 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -217,7 +217,9 @@ pub(super) fn option_fields(ui: &mut egui::Ui, d: &mut Dialog, screens: bool) { } ui.end_row(); choice(ui, d, "encoding", tl!("Encoding:"), &ENCODINGS, None); - choice(ui, d, "units", tl!("Units:"), &UNITS, None); + // Responsive omits width and height, so the unit has nothing to act on: show it dimmed. + let (units, responsive) = (d.str("units"), d.bool("responsive")); + choice(ui, d, "units", tl!("Units:"), &UNITS, responsive.then_some(units.as_str())); }); ui.add_space(6.0); ui.horizontal(|ui| { From d20787b36fee36bae5eeac3b1bcfc97d3ce3d062 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:51:03 +0430 Subject: [PATCH 03/71] docs: restore the status lines damaged by merges (main's line plus this PR's note) --- docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index af005ed382..38a95b0821 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (EPS and `.ai` editing data: a transparency set inside a clipping group stays after its `Q`; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x; SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: native format: dynamic symbols, #4938) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG export can write width and height in mm, cm, in or pt (#4462); EPS and `.ai` editing data: a transparency set inside a clipping group stays after its `Q`; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public diff --git a/docs/gaps.md b/docs/gaps.md index 8f31cba617..ad0b113cf9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (SVG export can write width and height in mm, cm, in or pt (#4462); Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8086a58a61..04fb6ce1bd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Type core options status and Kashidas feature revision corrected; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (SVG export can write width and height in mm, cm, in or pt (#4462); the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f2102af7ec..849a34049d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (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; Type on a Path Options has a Preview checkbox, #5360; the Action Options row cites the public Actions panel page; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x; SVG export writes width and height in mm, cm, in or pt, #4462; scores and estimates unchanged; previously: Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG export can write width and height in mm, cm, in or pt (#4462); 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) ## Feature submission evidence From b671c0bb8f8a59333833944ce7ffdbfb8cf36cab Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:37:00 +0430 Subject: [PATCH 04/71] Preserve physical SVG scale independently of coordinate precision --- crates/engine/src/cmd/fileio/tests_svg.rs | 20 ++++++------- crates/svg/src/lib.rs | 34 +++++++++++------------ crates/svg/tests/it/roundtrip.rs | 26 +++++++++++++++++ docs/target-app-parity.md | 6 ++-- 4 files changed, 56 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 0af38d2821..3af795f847 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -102,20 +102,20 @@ fn svg_export_writes_width_height_with_the_requested_unit() { let plain = svg(&mut s, json!({})); assert!(plain.contains(" width=\"200\" height=\"100\" viewBox=\"0 0 200 100\""), "{plain}"); assert_eq!(svg(&mut s, json!({"units": "px"})), plain, "px is the default, byte for byte"); - for (unit, size) in [ - ("mm", "width=\"70.556mm\" height=\"35.278mm\""), - ("cm", "width=\"7.056cm\" height=\"3.528cm\""), - ("in", "width=\"2.778in\" height=\"1.389in\""), - ("pt", "width=\"200pt\" height=\"100pt\""), - ] { - for p in [json!({"units": unit}), json!({"svg": {"units": unit}})] { - let out = svg(&mut s, p); - assert!(out.contains(&format!(" {size} viewBox=\"0 0 200 100\"")), "{unit}:\n{out}"); + for unit in ["mm", "cm", "in", "pt"] { + for decimals in [1, 3] { + for p in [json!({"units": unit, "decimals": decimals}), json!({"svg": {"units": unit, "decimals": decimals}})] { + let out = svg(&mut s, p); + assert!(out.contains(&format!("{unit}\"")) && out.contains("viewBox=\"0 0 200 100\""), "{unit}:\n{out}"); + let back = vectorcraft_svg::import(&out).unwrap(); + let rect = back.artboards[0].rect; + assert!((rect.width() - 200.0).abs() < 0.001 && (rect.height() - 100.0).abs() < 0.001, "{unit}: {rect:?}\n{out}"); + } } } let out = svg(&mut s, json!({"units": "mm", "responsive": true})); assert!(!out.contains("mm\"") && !out.contains("height=\"100\" viewBox") && out.contains("viewBox=\"0 0 200 100\""), "{out}"); - assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("width=\"70.6mm\" height=\"35.3mm\"")); + assert!(svg(&mut s, json!({"units": "mm", "decimals": 1})).contains("x=\"10.1\""), "coordinate precision is unchanged"); } #[test] diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index b4179d2bde..a8ba58d9ce 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -184,7 +184,8 @@ impl Encoding { /// The `viewBox` stays in user units (points) whatever is chosen. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum SizeUnit { - /// Bare numbers, CSS pixels at one per point (72 per inch). + /// Legacy bare numbers, unchanged: one per document point. CSS pixels are 96 per inch; + /// choose an explicit physical unit to preserve the document's physical size. #[default] #[serde(rename = "px")] Px, @@ -210,20 +211,14 @@ impl SizeUnit { } } - /// `points` as a length in this unit, rounded to `decimals` places, e.g. `70.556mm`. A - /// positive size never rounds to zero (a zero `width` disables rendering): in a unit with a - /// suffix it gets more places, up to 12, until a digit survives. `px` stays as [`fmt_num`] - /// writes it. + /// `points` as a length in this unit. Physical sizes use at least six decimal places and + /// six significant digits, independent of coordinate precision, so rounding does not change + /// the viewBox's rendered scale. `px` keeps [`fmt_num`]'s selected `decimals`. pub fn length(self, points: f64, decimals: u8) -> String { - const MAX_PLACES: u8 = 12; let (scale, suffix) = self.per_point(); let v = points * scale; - let mut places = decimals; - if !suffix.is_empty() && v.is_finite() && v > 0.0 { - while places < MAX_PLACES && fmt_num(v, places) == "0" { - places += 1; - } - } + let places = + if !suffix.is_empty() && v.is_finite() && v != 0.0 { decimals.max(6).max((5.0 - v.abs().log10().floor()) as u8) } else { decimals }; format!("{}{suffix}", fmt_num(v, places)) } } @@ -783,12 +778,15 @@ mod tests { } #[test] - fn tiny_physical_sizes_never_format_as_zero() { - // 3 pt is 0.0417 in: one place would write `0in`, and a zero width disables rendering. - assert_eq!(SizeUnit::In.length(3.0, 1), "0.04in"); - assert_eq!(SizeUnit::Mm.length(0.001, 1), "0.0004mm"); - // Nothing to widen when a digit survives, or when the size really is zero. - assert_eq!(SizeUnit::In.length(72.0, 1), "1in"); + fn tiny_physical_sizes_keep_their_scale() { + for unit in [SizeUnit::Pt, SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In] { + let (scale, suffix) = unit.per_point(); + for points in [200.0, 10.0, 3.0, 0.001, 1e-14, 1e-30] { + let written = unit.length(points, 1); + let value: f64 = written.strip_suffix(suffix).unwrap().parse().unwrap(); + assert!((value / scale / points - 1.0).abs() < 1e-5, "{points}pt: {written}"); + } + } assert_eq!(SizeUnit::In.length(0.0, 1), "0in"); // `px` is written exactly as `fmt_num` does. assert_eq!(SizeUnit::Px.length(3.0, 1), "3"); diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index b316b84359..2e2ad8d48b 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -682,6 +682,32 @@ fn svg_in_physical_units_reopens_at_the_same_size() { } } +/// A viewer's default `meet` scaling must preserve the artwork's physical extent, not just +/// reopen an artboard with roughly the right width and height. +#[test] +fn physical_units_preserve_rendered_extent_at_low_coordinate_precision() { + for (width, height, decimals) in [(200.0, 10.0, 1), (10.0, 200.0, 1), (0.2, 0.1, 1), (0.002, 0.001, 3)] { + let mut d = Document::new(width, height); + let n = rect_node(&mut d, Rect::new(0.0, 0.0, width, height), Appearance::basic(solid("#000000"), Paint::None, 0.0)); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, n).unwrap(); + for units in [SizeUnit::Mm, SizeUnit::Cm, SizeUnit::In, SizeUnit::Pt] { + let svg = export(&d, &ExportOptions { units, decimals, ..Default::default() }); + let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap(); + let extent = tree.root().abs_bounding_box(); + // CSS consumers render physical lengths at 96 px/in, document geometry is 72 pt/in. + for (actual, expected) in [ + (tree.size().width(), width * 96.0 / 72.0), + (tree.size().height(), height * 96.0 / 72.0), + (extent.width(), width * 96.0 / 72.0), + (extent.height(), height * 96.0 / 72.0), + ] { + assert!((f64::from(actual) / expected - 1.0).abs() < 2e-5, "{units:?}: {actual} != {expected}\n{svg}"); + } + } + } +} + #[test] fn unique_sanitized_ids() { let mut d = Document::new(200.0, 200.0); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 26db115ea8..d89fd2a1b4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (SVG export can write width and height in mm, cm, in or pt (#4462; ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (physical SVG dimensions retain scale independently of coordinate precision; disable Responsive and select physical units for physical output; previously: SVG export can write width and height in mm, cm, in or pt (#4462; ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -1391,6 +1391,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.svgz` file copied in a file manager pastes as its art, as a copied `.svg` file does. SVG export (Save As, Export As, Export for Screens, Asset Export and the clipboard share the writer) writes simple shapes as SVG basic shapes, as the reference app does (an ellipse is an `ellipse` tag until an anchor is added, [forum](https://community.adobe.com/t5/illustrator-discussions/trouble-exporting-shape-with-points-to-svg/td-p/10720325); rectangles come out as `<rect>` and `<polygon>`, [forum](https://community.adobe.com/t5/illustrator-discussions/force-svg-export-using-all-lt-rect-gt/td-p/11282378)): an axis-aligned rectangle as `<rect>`, a circle or ellipse drawn with four standard arcs as `<circle>`/`<ellipse>`, a straight line as `<line>`, and other straight-segment paths as `<polygon>`/`<polyline>`, at the written precision (#4652). A rectangle or ellipse with a dashed stroke, whose dashes would start elsewhere, a turned ellipse, curves and compound paths stay `<path>`. `crates/svg/tests/it/basic_shapes.rs` checks each element, that the picture renders as the canvas does and that the geometry reimports. At a precision of 9 decimals or fewer, SVG export writes each number from an integer when the integer rounds it as the decimal formatter does; the formatter still writes values halfway between two written numbers and values too large for the integer. Exporting one path of 200,000 anchors takes a median of 43.4 ms instead of 167.0 ms on Windows 11, and 20,000 rectangles 81.4 ms instead of 141.4 ms, with the same SVG (`crates/svg/src/lib.rs`). + Physical SVG sizes require both disabling SVG Options › Responsive and selecting Points, Millimeters, Centimeters or Inches under Units; Responsive omits `width` and `height`, so selecting a unit alone does not set physical size. Physical dimensions retain at least six decimal places and six significant digits independently of coordinate precision. Legacy Pixels output remains bare numbers, one per document point, rather than a physical-size guarantee: CSS pixels are 96 per inch. Regression coverage: `physical_units_preserve_rendered_extent_at_low_coordinate_precision` checks a consumer's viewport and drawn extent under default aspect-ratio scaling, including narrow and tiny artboards; `tiny_physical_sizes_keep_their_scale` covers smaller converted lengths. SVG import reads each `<circle>` and `<ellipse>` as the ellipse VectorCraft draws: four smooth anchors on the axes, starting at the right, with handles of the standard length, so an ellipse exported as `<ellipse>` comes back with the anchors it was written from and draws the same (`circles_and_ellipses_import_as_the_ellipse_drawn` in `crates/svg/tests/it/basic_shapes.rs`, `filled_ellipse_on_the_artboard_edge_survives_visually` in `prop_svg.rs`). SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). @@ -1972,7 +1973,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | +| 2026-11-11 | minor | SVG physical dimensions retain scale independently of coordinate precision, including tiny sizes (#5450 review); consumer-rendered extent regression added. Clarify that physical output requires Responsive off and a physical unit; legacy bare numeric output is unchanged and CSS pixels are 96/in. Scores and estimates unchanged. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for exported `width` and `height`. For physical size in laser and plotter software, disable Responsive and select a physical unit; Responsive omits both dimensions, so selecting a unit alone does not help (#4462; Pixels still bare numbers as before). Scores and estimates unchanged. | | 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | From 8fe7b5dcb105a48274026106bc2862dc5175a848 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:54:48 +0430 Subject: [PATCH 05/71] docs/gaps: SVG units entry says Responsive must be off and that bare px does not keep physical size --- docs/gaps.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index ee3bdbb0b4..0e9c8248e1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -391,8 +391,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi along it, bounded by each cluster's extent so a run of tiny level segments keeps its length); regression tests in `crates/pathops/src/planar.rs`. Estimate unchanged. - **Done (2026-11-03):** SVG export writes `width` and `height` in the unit SVG Options › Units (`units`) names: `px` - (bare numbers, as before), `pt`, `mm`, `cm` or `in`, with the `viewBox` in points, so laser and plotter software reads - the physical size (#4462); an unknown unit is an error. Estimate unchanged. + (bare numbers, as before; CSS pixels are 96 per inch, so they do not keep the physical size), `pt`, `mm`, `cm` or `in`, with + the `viewBox` in points, so laser and plotter software reads the physical size (#4462); to export physical dimensions turn + Responsive off and choose `pt`, `mm`, `cm` or `in` (Responsive omits `width` and `height`); an unknown unit is an error. + Estimate unchanged. - **Missing:** SVG units reverting to points (#864). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) are done. @@ -905,7 +907,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before; to export physical dimensions turn Responsive off and choose Points, Millimeters, Centimeters or Inches, since Responsive omits `width` and `height`); scores and estimates unchanged | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-14 | minor | Type: Middle Eastern & South Asian and Standard composers per paragraph (#4935): Paragraph panel menu, paragraph styles, `text.setFormat {composer}` and the native file; the Standard composers set Indic, Arabic and Hebrew type glyph by glyph. `.ai`, EPS and PDF files carry no composer. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | From 48f5ec0c5decaf2ca02931efecd67e2031bfe754 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:27:16 +0430 Subject: [PATCH 06/71] fix(svg): validate nested option keys from the format registry - Derive accepted SVG keys from the canonical format options, not serialized defaults that omit optional units. - Keep existing flat/nested precedence, document-unit inheritance and typed null rejection unchanged. --- crates/engine/src/cmd/params.rs | 9 ++++----- docs/target-app-parity.md | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8e7d7f7b0f..f55bc77994 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -906,11 +906,10 @@ fn option_trees() -> Value { let mut trees = pdf_option_tree(); if let Some(tree) = trees.as_object_mut() { tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default()); - let mut svg = serde_json::to_value(vectorcraft_svg::ExportOptions::default()).unwrap_or_default(); - if let Some(svg) = svg.as_object_mut() { - svg.extend(super::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]).map(|k| (k.to_string(), Value::Null))); - } - tree.insert("svg".into(), svg); + // Serialized defaults omit optional overrides such as units; the registry lists every key. + let svg = super::fileio::FORMATS.iter().find(|f| f.id == "svg").into_iter().flat_map(|f| f.options); + let svg = svg.filter(|o| o.name != "svg").map(|o| (o.name.to_string(), Value::Null)).collect(); + tree.insert("svg".into(), Value::Object(svg)); } trees } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 12e4bbc5c0..9d3d10694a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -8,7 +8,7 @@ > > Glyphs update (#5514): Alternates for Current Selection applies a variant's OpenType feature to that letter alone (`salt=2`) so an Arabic word stays joined; Entire Font lists unencoded glyphs. A positional variant no supported feature draws can be applied as a glyph choice (#6084). Entire Font uses the selection's font version and variable axes, and the default cell remains available after an unlisted choice even without GSUB alternates. Only Arabic presentation-form characters insert their joining base letter. Scores and estimates unchanged. > -> SVG physical dimensions update (#5450): explicit SVG Options write width and height in mm, cm, in or pt (#4462), retaining scale independently of coordinate precision, including tiny sizes. Without an override, export retains the document's units (#864). Responsive omits dimensions; explicit Pixels keeps bare numbers and CSS pixels are 96/in. Scores and estimates unchanged. +> SVG physical dimensions update (#5450): explicit SVG Options write width and height in mm, cm, in or pt (#4462), retaining scale independently of coordinate precision, including tiny sizes. Commands accept flat `units` or nested `svg.units`; nested values win and explicit null is rejected. Without an override, export retains the document's units (#864). Responsive omits dimensions; explicit Pixels keeps bare numbers and CSS pixels are 96/in. Scores and estimates unchanged. > > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). > From f06f957892acea426b798f80b529cf6fe9e2e4ba Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:11:15 +0430 Subject: [PATCH 07/71] Isolate PR notes from upstream update boundaries - Preserve PR wording and historical dates while moving only its own note away from actively edited summary/date-boundary lines. - No production source or Cargo changes; this is documentation placement, not a main-sync commit. --- docs/gaps.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index 0e3ca51235..fbfec79861 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -7,11 +7,12 @@ > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. -> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. ## Feature submission evidence +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. From 5183573f0460dde5c912f1a0a6c450d1c1157c14 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:22:04 +0430 Subject: [PATCH 08/71] Keep historical revision notes off the live table front - Relocate existing PR records verbatim into their historical date groups in the parity and roadmap tables. - Preserve production source, Cargo and recorded proof status; no additional upstream source merge. --- docs/file-format-parity.md | 2 +- docs/ui-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index e91313a8e2..9740c5139f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -386,7 +386,6 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; scores and estimates unchanged. | | 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | @@ -408,6 +407,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-11 | minor | Newly imported SVG/SVGZ titles use the imported-text rules: generated Untitled names and control-only titles give the filename fallback, other control characters are removed, and titles are limited to 65,536 characters. Native and Preserve Editing titles remain unchanged (#3626). | | 2026-11-11 | minor | Native and Preserve Editing restores keep an existing File Info title exactly, including repeated spaces; imported-text fallback titles alone are normalized (#3626). | | 2026-11-03 | minor | An imported document's own title goes into File Info only (#3626): an SVG's root `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title` else its Info `Title` is File Info's title (`metadata.title` in the native format, left out when unset so other documents save unchanged and older versions ignore it; written by exports); the document's name, which the tab, Save As and the default export names use, stays the file's name. | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | `.ai` and EPS import, and what SVG export, PDF export and `.ai` save draw: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as a `.ai`'s own page aligns them (see type-parity.md, same date). In 224 users' files (used locally, never committed), 63 render differently: 54 closer to the page, 7 further, 1 alike and 1 that couldn't be compared; among them the median share of pixels that differ from the page went from 4.4% to 1.0%. Of the 7: one now opens from its layers instead of its PDF part (they differ from the page by less than the import's 5% limit now; type note 3.8%); one has a centred line whose spacing inside it differs from the page's, which now centres on the page's line while half of it no longer lies on the page's glyphs (type note 1.4% to 2.4%); five moved by less than 0.05 of a percentage point, in type the page draws in other glyphs. The type note shows a smaller share in 6 files; 2 more envelopes of type open live (129 to 131, none fewer in any file). SVG import: `text-anchor` aligns a line's advance, which ends after its last character's letter spacing, so a centred or right-aligned letter-spaced line moves back by half or all of it and stays where a reader draws it; SVG export, which anchors lines so, reads back unchanged (test `import_text::anchored_letter_spaced_lines_stay_where_a_reader_draws_them`). Affinity import: centred or right-aligned tracked artistic text moves by half or all of its last character's tracking, as layout now aligns it (unverified against Affinity, whose files we don't have), and differently aligned paragraphs line up by the widths layout aligns them by (`affinity_features::artistic_text_aligns_its_lines_within_the_longest`). Scores and estimates unchanged. (#6610) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 03e4afd774..0cae40e1b4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -606,7 +606,6 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | @@ -657,6 +656,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | +| 2026-11-03 | minor | SVG Options has a Units choice (Pixels, Points, Millimeters, Centimeters, Inches) for the `width` and `height` an export writes, so laser and plotter software read the physical size (#4462; the `units` option, Pixels still bare numbers as before); scores and estimates unchanged | | 2026-11-03 | minor | Symbol editing draws and drags 9-slice guides on the canvas (#5280). Guides outside the artwork remain unsupported. Scores and hours remain unchanged. | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Object › Image Trace › Batch Trace Folder asks for a source and a destination folder and traces each image into it (#4921); scores and estimates unchanged | From 80d8acf7f96ae2238ee0c81e3ddfcac4b8f4a5e6 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:25:25 +0430 Subject: [PATCH 09/71] fix(engine): remove needless borrow of profile parser closure - Pass the reusable parser closure directly to Option::map without changing profile-choice handling. Fixes #8679 --- crates/engine/src/cmd/colormgmt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0ac4f8c3b0..bfaece3d77 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -1003,7 +1003,7 @@ impl PasteProfile { if o.keys().any(|k| k != "rgb" && k != "cmyk") { return Err(refuse()); } - let model = |m: &str| o.get(m).map(&one).transpose(); + let model = |m: &str| o.get(m).map(one).transpose(); Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? })) } Some(v) => { From 64211808de18357274a46d7f8517d2af6eeeaea7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 19 Nov 2026 16:13:48 -0800 Subject: [PATCH 10/71] Quick Pen: Ctrl+wheel over the canvas changes the arc size With the Quick Pen tool active, Ctrl with a scroll on a touchpad over the canvas (the Control key on macOS too) changes the arc size as ] and [ do: up makes it 15 degrees larger and down 15 degrees smaller, for the last sharp-corner arc and the arcs after it, also while a press drags that arc. The touchpad makes one step for each wheel line of motion within one turn, and momentum after the fingers lift makes none; the keys held at any point of a gesture count until it ends. A mouse wheel turned with Ctrl does the same, one step for each wheel event. Sideways motion makes no step. The view does not zoom or scroll for the rest of that wheel turn. The arc size stays as it is for a wheel turned over the Quick Pen toolbar, under a modal dialog, in a turn begun under one, or with Shift, Alt or Cmd held as well. - New desktop commands tool.quickPen.arcLarger and tool.quickPen.arcSmaller step the size; each returns false when the Quick Pen tool is not active or the step would leave 1 to 359 degrees. - Labels in every catalog. - The command palette test that needs a short result list searches "pen tools": the new commands also match "pen tool", which then fills all twelve rows, so the popup can no longer grow. Docs: docs/mcp.md, ROADMAP, docs/ui-parity.md, docs/target-app-parity.md. Part of #2660. --- ROADMAP.md | 1 + crates/mcp/src/ui_catalog.rs | 12 + crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/canvas/input.rs | 7 +- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 125 ++++++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/menus/run.rs | 33 ++ crates/ui-egui/src/menus/ui_commands.rs | 12 + crates/ui-egui/src/palette.rs | 2 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/quickpenwheel.rs | 407 +++++++++++++++++++ docs/mcp.md | 21 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 41 files changed, 672 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/canvas/quick_pen_wheel.rs create mode 100644 crates/ui-egui/src/tests/quickpenwheel.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..b7ecbca46f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -149,6 +149,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen arc size with Ctrl+wheel: over the canvas, a touchpad scroll or a mouse wheel turned with Ctrl makes the arc size 15° larger or smaller per step, as `]` and `[` do, and the view stays put (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`; part of #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 64c57a6798..548f10b79f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -718,6 +718,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", ), + ( + "tool.quickPen.arcLarger", + "Increase Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° larger, for the last sharp-corner arc of the path being drawn and the arcs after it, as ] and Ctrl+wheel up over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size above 359°", + ), + ( + "tool.quickPen.arcSmaller", + "Decrease Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° smaller, for the last sharp-corner arc of the path being drawn and the arcs after it, as [ and Ctrl+wheel down over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size below 1°", + ), ( "window.dock", "Panels", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..09dbd5e07a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -29,6 +29,7 @@ mod outline; mod overlays; mod panes; mod quick_pen_bar; +mod quick_pen_wheel; mod raster; mod selection_marks; mod task_bar; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..f91a29d63f 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -248,7 +248,12 @@ fn wheel_view( if carried != was_carried { ui.data_mut(|d| d.insert_temp(carried_id, carried)); } - let muted = modal || carried; + // A Ctrl-wheel turn with the Quick Pen tool changes its arc size and leaves the view alone. + // Not over a floating panel, a menu or a toolbar drawn on top of the canvas ([`on_canvas`]), and not for a + // wheel turn that went on under a modal dialog. + let over = !modal && !carried && resp.hovered() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| on_canvas(ui, resp, p)); + let arc_turn = super::quick_pen_wheel::arc_size(app, ui, over); + let muted = modal || carried || arc_turn; let navigates = resp.hovered() && !muted; // A docked field may be drawn later and has not consumed its wheel event yet. Only canvas // hover may start a zoom glide; existing glides still decay outside the canvas in `wheel`. diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs new file mode 100644 index 0000000000..6ba86ca852 --- /dev/null +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -0,0 +1,125 @@ +//! Ctrl+wheel over the canvas with the Quick Pen tool: the arc size, in place of the view. +//! +//! Public behavior: Ctrl + scroll on a trackpad makes the arc size larger or smaller, on Windows +//! and on macOS alike +//! ([Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)). +//! VectorCraft's own rules: a mouse wheel turned with Ctrl does the same; each wheel event from a +//! mouse wheel (one per notch) makes one step of 15°, as `[` and `]` do, and a touchpad makes one +//! step for each wheel line of its motion; up makes the arc larger and down smaller, and sideways +//! motion makes no step; momentum after +//! the fingers lift makes no step; and a turn ends as egui's scroll turns do (0.15 s without a wheel +//! event, 1 s while a touchpad gesture is under way). + +use super::view::fine_steps; +use super::{Ui, VectorcraftApp, json}; + +/// A wheel turn the Quick Pen tool may take: the motion, in wheel lines, not yet turned into a +/// step; whether the tool took the turn; whether a touchpad gesture is under way (between its Start +/// and End phases); when the turn's last wheel event came (egui's input time); whether a touchpad +/// sent it; and the modifiers the turn holds. +#[derive(Clone, Copy, Default, PartialEq)] +struct ArcWheel { + rest: f32, + taken: bool, + gesture: bool, + last: f64, + trackpad: bool, + held: egui::Modifiers, +} + +/// Seconds without a wheel event after which a wheel event starts a new turn, as egui's own scroll +/// timeouts: 1 s while a touchpad gesture is under way (fingers resting mid-gesture), else 0.15 s. +const TURN_GAP: f64 = 0.150; +const GESTURE_GAP: f64 = 1.0; + +/// Most steps one frame makes: from 1° to 359° is fewer than 24 steps of 15°. +const MOST_STEPS: i32 = 24; + +/// Ctrl alone (the Control key on macOS too). +fn ctrl_alone(m: egui::Modifiers) -> bool { + m.ctrl && !(m.alt || m.shift || m.mac_cmd) +} + +/// With the Quick Pen tool active and the pointer over the canvas (`over`), each wheel event from a +/// mouse wheel turned with Ctrl held makes the arc size one step larger (up) or smaller (down), and a +/// touchpad's motion makes one step per wheel line of it. Momentum after the fingers lift makes no +/// step. Returns true while such a turn goes on, so the view does not zoom or scroll for the rest of +/// it. +pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, over: bool) -> bool { + let id = egui::Id::unique("quick-pen-arc-wheel"); + let before: ArcWheel = ui.data(|d| d.get_temp(id)).unwrap_or_default(); + let line = ui.ctx().options(|o| o.input_options.line_scroll_speed).max(1.0); + let takes = over && app.session.tool_id() == vectorcraft_tools::quickpen::ID; + let mut now = before; + let (any, scrolling) = ui.input(|i| { + let mut any = false; + for e in &i.events { + let egui::Event::MouseWheel { unit, delta, phase, modifiers, source } = e else { continue }; + any = true; + // A wheel event after egui's scroll timeout, or a touchpad gesture's start, begins a + // new turn: what the turn before it took and left over goes. + let gap = if now.gesture && now.trackpad { GESTURE_GAP } else { TURN_GAP }; + if i.time - now.last > gap || *phase == egui::TouchPhase::Start { + now = ArcWheel::default(); + } + now.last = i.time; + now.trackpad = *source == egui::MouseWheelSource::Trackpad; + // The modifiers held at any point of a touchpad gesture count until it ends, as egui + // keeps them (Ctrl let go still counts, and Shift added stays added); otherwise the + // modifiers of each event count. + match phase { + egui::TouchPhase::Start => { + now.gesture = true; + now.held = *modifiers; + } + egui::TouchPhase::Move if now.gesture => now.held |= *modifiers, + egui::TouchPhase::Move => now.held = *modifiers, + egui::TouchPhase::End | egui::TouchPhase::Cancel => now.gesture = false, + } + if !(takes && ctrl_alone(now.held)) { + continue; + } + now.taken = true; + // Only Move events move, as egui's scroll; momentum after the fingers lift makes no step. + if *phase != egui::TouchPhase::Move || *source == egui::MouseWheelSource::Momentum { + continue; + } + // A mouse wheel's event is one step, whatever it reports (a browser reports a notch in + // points, and a system may scale a fast turn's lines); a touchpad's fine motion steps + // once per wheel line of it. [`fine_steps`] tells them apart, as for the view. Only up + // and down motion counts. + let s = delta.y; + let d = if !fine_steps(*unit, *delta, *source) { + if s == 0.0 { 0.0 } else { s.signum() } + } else if *unit == egui::MouseWheelUnit::Point { + s / line + } else { + s + }; + if d.is_finite() { + now.rest += d; + } + } + (any, i.is_scrolling()) + }); + if !any && !scrolling { + now = ArcWheel::default(); + } + let steps = now.rest.trunc(); + now.rest -= steps; + let (cmd, n) = if steps > 0.0 { ("tool.quickPen.arcLarger", steps) } else { ("tool.quickPen.arcSmaller", -steps) }; + for _ in 0..(n as i32).min(MOST_STEPS) { + match app.run(cmd, json!({})) { + Ok(serde_json::Value::Bool(true)) => {} + Ok(_) => break, + Err(e) => { + app.ui.status = e; + break; + } + } + } + if now != before { + ui.data_mut(|d| d.insert_temp(id, now)); + } + now.taken +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 1ffb352a36..fae08e2e60 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2718,6 +2718,8 @@ font-technology Variable Променливи Continuous Arc Непрекъсната дъга Sharp Corner Arc Дъга с остър ъгъл Flip Arc Обръщане на дъгата + Increase Arc Size Увеличаване на размера на дъгата + Decrease Arc Size Намаляване на размера на дъгата Hide Toolbar Скриване на лентата с инструменти Pin Toolbar Position Закачане на позицията на лентата с инструменти Reset Toolbar Position Нулиране на позицията на лентата с инструменти diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 712106379f..33c34cd2b8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4223,6 +4223,8 @@ theme Appearance Izgled Continuous Arc Neprekidni luk Sharp Corner Arc Luk s oštrim uglom Flip Arc Preokreni luk + Increase Arc Size Povećaj veličinu luka + Decrease Arc Size Smanji veličinu luka Hide Toolbar Sakrij traku s alatima Pin Toolbar Position Prikvači položaj trake s alatima Reset Toolbar Position Vrati položaj trake s alatima na početno diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 70b7cbf8ee..ecf0120f0d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3474,6 +3474,8 @@ digits Malayalam Malaiàlam Continuous Arc Arc continu Sharp Corner Arc Arc de cantonada aguda Flip Arc Inverteix l’arc + Increase Arc Size Augmenta la mida de l’arc + Decrease Arc Size Redueix la mida de l’arc Hide Toolbar Amaga la barra d’eines Pin Toolbar Position Fixa la posició de la barra d’eines Reset Toolbar Position Restableix la posició de la barra d’eines diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9ef6f066e6..384be3cbe3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4330,6 +4330,8 @@ theme Appearance Motiv Continuous Arc Plynulý oblouk Sharp Corner Arc Oblouk s ostrým rohem Flip Arc Překlopit oblouk + Increase Arc Size Zvětšit velikost oblouku + Decrease Arc Size Zmenšit velikost oblouku Hide Toolbar Skrýt panel nástrojů Pin Toolbar Position Připnout polohu panelu nástrojů Reset Toolbar Position Obnovit polohu panelu nástrojů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0d8b14dba4..ed499ef918 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6787,6 +6787,8 @@ theme Appearance Udseende Continuous Arc Fortløbende bue Sharp Corner Arc Bue med skarpt hjørne Flip Arc Vend bue + Increase Arc Size Øg buestørrelse + Decrease Arc Size Formindsk buestørrelse Hide Toolbar Skjul værktøjslinjen Pin Toolbar Position Fastgør værktøjslinjens placering Reset Toolbar Position Nulstil værktøjslinjens placering diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bd04b8cc19..f30781515c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2780,6 +2780,8 @@ file-filter Templates Vorlagen Continuous Arc Fortlaufender Bogen Sharp Corner Arc Bogen mit scharfer Ecke Flip Arc Bogen spiegeln + Increase Arc Size Bogengröße erhöhen + Decrease Arc Size Bogengröße verringern Hide Toolbar Werkzeugleiste ausblenden Pin Toolbar Position Position der Werkzeugleiste fixieren Reset Toolbar Position Position der Werkzeugleiste zurücksetzen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 220e9dede3..229231f0ef 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2184,6 +2184,8 @@ font-technology Variable Μεταβλητές Continuous Arc Συνεχές τόξο Sharp Corner Arc Τόξο με αιχμηρή γωνία Flip Arc Αναστροφή τόξου + Increase Arc Size Αύξηση μεγέθους τόξου + Decrease Arc Size Μείωση μεγέθους τόξου Hide Toolbar Απόκρυψη γραμμής εργαλείων Pin Toolbar Position Σταθεροποίηση θέσης γραμμής εργαλείων Reset Toolbar Position Επαναφορά θέσης γραμμής εργαλείων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 016f297b3b..6da28fcf82 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2821,6 +2821,8 @@ font-technology Variable Variables Continuous Arc Arco continuo Sharp Corner Arc Arco de esquina aguda Flip Arc Voltear arco + Increase Arc Size Aumentar tamaño del arco + Decrease Arc Size Reducir tamaño del arco Hide Toolbar Ocultar barra de herramientas Pin Toolbar Position Fijar posición de la barra de herramientas Reset Toolbar Position Restablecer posición de la barra de herramientas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 46b3fbf1d5..6582281378 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4247,6 +4247,8 @@ theme Appearance Ulkoasu Continuous Arc Jatkuva kaari Sharp Corner Arc Terävän kulman kaari Flip Arc Käännä kaari + Increase Arc Size Suurenna kaaren kokoa + Decrease Arc Size Pienennä kaaren kokoa Hide Toolbar Piilota työkalurivi Pin Toolbar Position Kiinnitä työkalurivin sijainti Reset Toolbar Position Palauta työkalurivin sijainti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4ce31cfc06..887311455f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2809,6 +2809,8 @@ font-technology Variable Variables Continuous Arc Arc continu Sharp Corner Arc Arc à angle vif Flip Arc Retourner l’arc + Increase Arc Size Augmenter la taille de l’arc + Decrease Arc Size Réduire la taille de l’arc Hide Toolbar Masquer la barre d’outils Pin Toolbar Position Épingler la position de la barre d’outils Reset Toolbar Position Réinitialiser la position de la barre d’outils diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f1ad753245..733f7f5e04 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2827,6 +2827,8 @@ Continuous Arc સતત આર્ક Sharp Corner Arc તીક્ષ્ણ ખૂણાવાળો આર્ક Flip Arc આર્ક ફ્લિપ કરો + Increase Arc Size આર્કનું કદ વધારો + Decrease Arc Size આર્કનું કદ ઘટાડો Hide Toolbar ટૂલબાર છુપાવો Pin Toolbar Position ટૂલબાર સ્થિતિ પિન કરો Reset Toolbar Position ટૂલબાર સ્થિતિ રીસેટ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index c8852f1ddd..d8b632fefd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4021,6 +4021,8 @@ arrowhead Feather पंख Continuous Arc सतत आर्क Sharp Corner Arc तीखे कोने वाला आर्क Flip Arc आर्क पलटें + Increase Arc Size आर्क का आकार बढ़ाएँ + Decrease Arc Size आर्क का आकार घटाएँ Hide Toolbar टूलबार छिपाएँ Pin Toolbar Position टूलबार स्थिति पिन करें Reset Toolbar Position टूलबार स्थिति रीसेट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 54ff192eed..08a100ae60 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3350,6 +3350,8 @@ file-filter Templates Sablonok Continuous Arc Folytonos ív Sharp Corner Arc Éles sarkú ív Flip Arc Ív tükrözése + Increase Arc Size Ívméret növelése + Decrease Arc Size Ívméret csökkentése Hide Toolbar Eszköztár elrejtése Pin Toolbar Position Eszköztár helyének rögzítése Reset Toolbar Position Eszköztár helyének visszaállítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9a0f622d21..2c4d277610 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4655,6 +4655,8 @@ theme Appearance Tampilan Continuous Arc Busur bersambung Sharp Corner Arc Busur sudut tajam Flip Arc Balik busur + Increase Arc Size Perbesar ukuran busur + Decrease Arc Size Perkecil ukuran busur Hide Toolbar Sembunyikan bilah alat Pin Toolbar Position Sematkan posisi bilah alat Reset Toolbar Position Atur ulang posisi bilah alat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 190b136a06..50db260c8a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2865,6 +2865,8 @@ file-filter Templates Modelli Continuous Arc Arco continuo Sharp Corner Arc Arco ad angolo vivo Flip Arc Capovolgi arco + Increase Arc Size Aumenta dimensione arco + Decrease Arc Size Riduci dimensione arco Hide Toolbar Nascondi barra degli strumenti Pin Toolbar Position Fissa posizione barra degli strumenti Reset Toolbar Position Ripristina posizione barra degli strumenti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 665e74c319..847716df08 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2955,6 +2955,8 @@ antiAlias Sharp シャープ Continuous Arc 連続円弧 Sharp Corner Arc 鋭角円弧 Flip Arc 円弧を反転 + Increase Arc Size 円弧のサイズを大きく + Decrease Arc Size 円弧のサイズを小さく Hide Toolbar ツールバーを隠す Pin Toolbar Position ツールバーの位置を固定 Reset Toolbar Position ツールバーの位置をリセット diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d3ea2160c1..6472689e0f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6068,6 +6068,8 @@ theme Appearance იერსახე Continuous Arc უწყვეტი რკალი Sharp Corner Arc მახვილკუთხიანი რკალი Flip Arc რკალის არეკვლა + Increase Arc Size რკალის ზომის გაზრდა + Decrease Arc Size რკალის ზომის შემცირება Hide Toolbar ხელსაწყოთა ზოლის დამალვა Pin Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამაგრება Reset Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამოყრა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0c2642f758..26fc1eeacd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2945,6 +2945,8 @@ antiAlias Sharp 날카롭게 Continuous Arc 연속 호 Sharp Corner Arc 뾰족한 모서리 호 Flip Arc 호 뒤집기 + Increase Arc Size 호 크기 늘리기 + Decrease Arc Size 호 크기 줄이기 Hide Toolbar 도구 모음 숨기기 Pin Toolbar Position 도구 모음 위치 고정 Reset Toolbar Position 도구 모음 위치 재설정 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c1f7e36426..670b00a5aa 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4655,6 +4655,8 @@ theme Appearance Vormgeving Continuous Arc Doorlopende boog Sharp Corner Arc Boog met scherpe hoek Flip Arc Boog spiegelen + Increase Arc Size Boog groter maken + Decrease Arc Size Boog kleiner maken Hide Toolbar Werkbalk verbergen Pin Toolbar Position Werkbalkpositie vastzetten Reset Toolbar Position Werkbalkpositie herstellen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5808ddb8c2..5478f6dd28 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4195,6 +4195,8 @@ theme Appearance Wygląd Continuous Arc Łuk ciągły Sharp Corner Arc Łuk z ostrym narożnikiem Flip Arc Odwróć łuk + Increase Arc Size Zwiększ rozmiar łuku + Decrease Arc Size Zmniejsz rozmiar łuku Hide Toolbar Ukryj pasek narzędzi Pin Toolbar Position Przypnij położenie paska narzędzi Reset Toolbar Position Resetuj położenie paska narzędzi diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2204a2bdc1..12749b8c83 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2323,6 +2323,8 @@ antiAlias Sharp Nítido Continuous Arc Arco Contínuo Sharp Corner Arc Arco de Canto Agudo Flip Arc Virar Arco + Increase Arc Size Aumentar Tamanho do Arco + Decrease Arc Size Diminuir Tamanho do Arco Hide Toolbar Ocultar Barra de Ferramentas Pin Toolbar Position Fixar Posição da Barra de Ferramentas Reset Toolbar Position Redefinir Posição da Barra de Ferramentas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b3ca5d5d93..2b40f73140 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2847,6 +2847,8 @@ file-filter Templates Шаблоны Continuous Arc Непрерывная дуга Sharp Corner Arc Дуга с острым углом Flip Arc Отразить дугу + Increase Arc Size Увеличить размер дуги + Decrease Arc Size Уменьшить размер дуги Hide Toolbar Скрыть панель инструментов Pin Toolbar Position Закрепить положение панели инструментов Reset Toolbar Position Сбросить положение панели инструментов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 94a83ef975..f2b71da213 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2742,6 +2742,8 @@ font-technology Variable Variabla Continuous Arc Kontinuerlig båge Sharp Corner Arc Båge med skarpt hörn Flip Arc Vänd båge + Increase Arc Size Öka bågstorlek + Decrease Arc Size Minska bågstorlek Hide Toolbar Dölj verktygsfältet Pin Toolbar Position Fäst verktygsfältets position Reset Toolbar Position Återställ verktygsfältets position diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2fcd6d3b54..4ed628133b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2591,6 +2591,8 @@ shape Open Açık Continuous Arc Sürekli Yay Sharp Corner Arc Keskin Köşeli Yay Flip Arc Yayı Çevir + Increase Arc Size Yay Boyutunu Artır + Decrease Arc Size Yay Boyutunu Azalt Hide Toolbar Araç Çubuğunu Gizle Pin Toolbar Position Araç Çubuğu Konumunu Sabitle Reset Toolbar Position Araç Çubuğu Konumunu Sıfırla diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 49f8383268..31fdb3c4dc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2857,6 +2857,8 @@ file-filter Templates Шаблони Continuous Arc Неперервна дуга Sharp Corner Arc Дуга з гострим кутом Flip Arc Відобразити дугу + Increase Arc Size Збільшити розмір дуги + Decrease Arc Size Зменшити розмір дуги Hide Toolbar Сховати панель інструментів Pin Toolbar Position Закріпити положення панелі інструментів Reset Toolbar Position Скинути положення панелі інструментів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 13d02e5184..d900872d1a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3170,6 +3170,8 @@ digits Hindi Hindi Continuous Arc Cung liên tục Sharp Corner Arc Cung góc nhọn Flip Arc Lật cung + Increase Arc Size Tăng kích thước cung + Decrease Arc Size Giảm kích thước cung Hide Toolbar Ẩn thanh công cụ Pin Toolbar Position Ghim vị trí thanh công cụ Reset Toolbar Position Đặt lại vị trí thanh công cụ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f51baaa7e7..43eae51e7c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2708,6 +2708,8 @@ file-filter Templates 模板 Continuous Arc 连续弧线 Sharp Corner Arc 尖角弧线 Flip Arc 翻转弧线 + Increase Arc Size 增大弧线尺寸 + Decrease Arc Size 减小弧线尺寸 Hide Toolbar 隐藏工具栏 Pin Toolbar Position 固定工具栏位置 Reset Toolbar Position 重置工具栏位置 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d794ea15d9..5f585aa79e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4151,6 +4151,8 @@ liquify-list-end {0}, {1} {0}和{1} Continuous Arc 連續弧線 Sharp Corner Arc 尖角弧線 Flip Arc 翻轉弧線 + Increase Arc Size 增大弧線尺寸 + Decrease Arc Size 減小弧線尺寸 Hide Toolbar 隱藏工具列 Pin Toolbar Position 釘選工具列位置 Reset Toolbar Position 重設工具列位置 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 8c2767e20b..1aabf9faf4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -725,6 +725,39 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< Err(e) => Err(e.to_string()), } } + "tool.quickPen.arcLarger" | "tool.quickPen.arcSmaller" => { + // `]` or `[`, for Ctrl+wheel over the canvas: the arc size 15° larger or smaller. Input + // held for an edit is finished first, as for Flip Arc. False, with nothing changed beyond + // that, while the Quick Pen tool is not active or the step would leave 1° to 359°. + match app.session.finish_tool_edit() { + Ok(reqs) => crate::canvas::apply_requests(app, Ok(reqs)), + Err(e) => return Some(Err(e.to_string())), + } + if app.session.tool_id() != vectorcraft_tools::quickpen::ID { + return Some(Ok(json!(false))); + } + let key = + if id == "tool.quickPen.arcLarger" { vectorcraft_tools::ToolKey::BracketRight } else { vectorcraft_tools::ToolKey::BracketLeft }; + // A step changes the tool's size, or draws the arc again: as an edit between presses, or + // as the preview of a drag (applied, or kept for the release with Real-time Drawing off). + let state = |app: &VectorcraftApp| { + let d = app.session.active(); + ( + app.session.tool_options()["turn"].clone(), + d.map(|d| d.revision), + d.and_then(|d| d.interaction.as_ref()).and_then(|it| it.preview.clone()), + ) + }; + let before = state(app); + let view = app.view_info(); + match app.session.tool_key(key, vectorcraft_tools::Mods::default(), view) { + Ok(reqs) => { + crate::canvas::apply_requests(app, Ok(reqs)); + Ok(json!(state(app) != before)) + } + Err(e) => Err(e.to_string()), + } + } "window.dock" => { let ui = &mut app.ui; // The bars the last Tab hid show again, unless the toolbar or the Control bar was shown diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ad562ecd6c..ccb4281794 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -719,6 +719,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", ), + ( + "tool.quickPen.arcLarger", + "Increase Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° larger, for the last sharp-corner arc of the path being drawn and the arcs after it, as ] and Ctrl+wheel up over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size above 359°", + ), + ( + "tool.quickPen.arcSmaller", + "Decrease Arc Size", + "", + "{} make the Quick Pen tool's arc size 15° smaller, for the last sharp-corner arc of the path being drawn and the arcs after it, as [ and Ctrl+wheel down over the canvas do; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active or a step would take the arc size below 1°", + ), ( "window.dock", "Panels", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..3f6883781c 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -5474,7 +5474,7 @@ mod tests { let mut window = Window::new(); window.app.ui.toolbar = false; window.app.ui.custom_toolbars.push(drawing_toolbar([100.0, 120.0])); - window.search("pen tool"); + window.search("pen tools"); let small = window.popup(); window.app.ui.custom_toolbars[0].pos = [small.center().x, small.bottom() + 2.0]; window.frame(vec![]); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..705ff99794 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -31,6 +31,7 @@ mod printps; mod printtiling; mod puppetwarp; mod quickpenbar; +mod quickpenwheel; mod recolor; mod recovery; pub(super) mod removeanchors; diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs new file mode 100644 index 0000000000..597035bc47 --- /dev/null +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -0,0 +1,407 @@ +//! Ctrl+wheel over the canvas with the Quick Pen tool changes the arc size and leaves the view as it +//! is; the arc size commands step it as `[` and `]` do. + +use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::SubPath; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::{VectorcraftApp, canvas}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("quickPen"); + app.run("tool.setOption", json!({"key": "action", "value": "sharpArc"})).unwrap(); + app +} + +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>) { + frame_at(app, ctx, events, None); +} + +/// [`frame`] at input `time` (seconds), when given. +fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>, time: Option<f64>) { + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, time, ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); +} + +/// A wheel turn over the middle of the canvas, then frames enough for egui to let out all of it. +fn turn(app: &mut VectorcraftApp, ctx: &egui::Context, unit: MouseWheelUnit, dy: f32, modifiers: Modifiers, source: MouseWheelSource) { + let at = app.canvas_rect.unwrap().center(); + let wheel = Event::MouseWheel { unit, delta: vec2(0.0, dy), phase: egui::TouchPhase::Move, modifiers, source }; + frame(app, ctx, vec![Event::PointerMoved(at), wheel]); + for _ in 0..40 { + frame(app, ctx, vec![]); + } +} + +fn click_doc(app: &mut VectorcraftApp, x: f64, y: f64) { + let v = app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } +} + +fn paths(app: &VectorcraftApp) -> Vec<SubPath> { + let mut v = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.extend(path.subpaths.iter().cloned()); + } + }); + v +} + +fn arc_size(app: &VectorcraftApp) -> f64 { + app.session.tool_options()["turn"].as_f64().unwrap() +} + +/// (zoom, center x, center y) of the view. +fn view(app: &VectorcraftApp) -> (f64, f64, f64) { + let v = app.view().unwrap(); + (v.zoom, v.center.x, v.center.y) +} + +/// Ctrl+wheel with the Quick Pen tool: a notch up makes the last sharp-corner arc 15° larger and a +/// notch down 15° smaller, each as one undo step, with Ctrl as Windows and Linux report it (with +/// Command) and as macOS reports the Control key (alone). A touchpad steps once per wheel line of +/// motion. The view neither zooms nor scrolls. +#[test] +fn ctrl_wheel_changes_the_arc_size_and_not_the_view() { + let mut app = app(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click_doc(&mut app, 100.0, 150.0); + click_doc(&mut app, 200.0, 150.0); + let drawn = paths(&app)[0].clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let still = view(&app); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let line = ctx.options(|o| o.input_options.line_scroll_speed); + + turn(&mut app, &ctx, MouseWheelUnit::Line, 1.0, ctrl, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 195.0); + assert_ne!(paths(&app)[0], drawn, "the last arc changed"); + assert_eq!(paths(&app).len(), 1); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + assert_eq!(view(&app), still, "Ctrl+wheel did not zoom or scroll"); + + let at = app.canvas_rect.unwrap().center(); + let notch = |dy: f32, modifiers| Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers, + source: MouseWheelSource::Wheel, + }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), notch(-1.0, Modifiers::CTRL), notch(-1.0, Modifiers::CTRL)]); + for _ in 0..40 { + frame(&mut app, &ctx, vec![]); + } + assert_eq!(arc_size(&app), 165.0, "two notches down with the macOS Control key"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 3); + assert_eq!(view(&app), still); + + // A mouse wheel's event is one step, whether the system scaled a fast turn's lines or reports a + // fraction of a line. + turn(&mut app, &ctx, MouseWheelUnit::Line, 4.5, ctrl, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 180.0, "a fast notch of four and a half lines"); + turn(&mut app, &ctx, MouseWheelUnit::Line, -0.3, ctrl, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 165.0, "a notch of three tenths of a line"); + // With Shift, Alt or Command added (Cmd on macOS), the wheel leaves the arc size. + for modifiers in [ + Modifiers { shift: true, ..ctrl }, + Modifiers { alt: true, ..ctrl }, + Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }, + Modifiers { mac_cmd: true, ..Modifiers::CTRL }, + ] { + turn(&mut app, &ctx, MouseWheelUnit::Line, 1.0, modifiers, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 165.0, "{modifiers:?}"); + } + turn(&mut app, &ctx, MouseWheelUnit::Line, 1.0, ctrl, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 180.0); + // Sideways motion leaves the arc size. + let sideways = Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(1.0, 0.0), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Wheel, + }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), sideways]); + for _ in 0..40 { + frame(&mut app, &ctx, vec![]); + } + assert_eq!(arc_size(&app), 180.0, "sideways"); + let still = view(&app); + + // Half a wheel line from a touchpad makes no step; the second half of the same turn makes one, + // and momentum after it makes none. + let steps = app.session.active().unwrap().history.undo.len(); + let at = app.canvas_rect.unwrap().center(); + let fine = |dy: f32, source| Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source, + }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), fine(line / 2.0, MouseWheelSource::Trackpad)]); + assert_eq!(arc_size(&app), 180.0); + frame(&mut app, &ctx, vec![fine(line / 2.0, MouseWheelSource::Trackpad)]); + assert_eq!(arc_size(&app), 195.0); + frame(&mut app, &ctx, vec![fine(3.0 * line, MouseWheelSource::Momentum)]); + assert_eq!(arc_size(&app), 195.0, "momentum makes no step"); + for _ in 0..40 { + frame(&mut app, &ctx, vec![]); + } + assert_eq!(view(&app), still); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one step and no piece"); + + // Without Ctrl the wheel scrolls the view and leaves the arc size. + turn(&mut app, &ctx, MouseWheelUnit::Line, 1.0, Modifiers::NONE, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 195.0); + assert_ne!(view(&app), still, "the wheel scrolled"); +} + +/// Ctrl+wheel while a press drags a sharp-corner arc: the arc being dragged takes the new size, the +/// drag goes on, and once the press is let go the piece and its size change are one undo step. +#[test] +fn ctrl_wheel_sizes_the_arc_being_dragged() { + let mut app = app(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click_doc(&mut app, 100.0, 150.0); + let undo = app.session.active().unwrap().history.undo.len(); + let c = app.canvas_rect.unwrap().center(); + let from = c + vec2(150.0, 80.0); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + let mut to = from; + for _ in 0..5 { + to += vec2(14.0, 0.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); + } + assert!(app.session.tool_busy(), "the press drags"); + let dragged = paths(&app)[0].clone(); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let notch = Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Wheel, + }; + frame(&mut app, &ctx, vec![notch]); + assert_eq!(arc_size(&app), 195.0); + assert!(app.session.tool_busy(), "the drag goes on"); + assert_eq!(paths(&app).len(), 1); + assert_ne!(paths(&app)[0], dragged, "the arc being dragged is drawn again with the new size"); + // The tool's size set ahead of the dragged arc's: a step that brings the arc to it still reports + // the change. + app.run("tool.setOption", json!({"key": "turn", "value": 210})).unwrap(); + let sized = paths(&app)[0].clone(); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(arc_size(&app), 210.0); + assert_ne!(paths(&app)[0], sized); + assert!(app.session.tool_busy()); + frame(&mut app, &ctx, vec![button(to, false)]); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + assert!(!app.session.tool_busy()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the piece and its size change are one undo step"); +} + +/// Ctrl+wheel over the Quick Pen toolbar, which floats over the canvas, leaves the arc size; half a +/// wheel line from a touchpad does not add to half a line from a later turn. +#[test] +fn ctrl_wheel_over_the_toolbar_or_in_two_turns_makes_no_step() { + let mut app = app(); + let ctx = egui::Context::default(); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let bar = canvas::quick_pen_bar_rect(&ctx).expect("the toolbar shows"); + let notch = |modifiers| Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers, + source: MouseWheelSource::Wheel, + }; + frame(&mut app, &ctx, vec![Event::PointerMoved(bar.center()), notch(ctrl)]); + for _ in 0..40 { + frame(&mut app, &ctx, vec![]); + } + assert_eq!(arc_size(&app), 180.0, "over the toolbar"); + + let line = ctx.options(|o| o.input_options.line_scroll_speed); + let at = app.canvas_rect.unwrap().center(); + let half = Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, line / 2.0), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Trackpad, + }; + // Two halves a second apart, with no frame in between. + frame_at(&mut app, &ctx, vec![Event::PointerMoved(at), half.clone()], Some(100.0)); + frame_at(&mut app, &ctx, vec![half.clone()], Some(101.0)); + assert_eq!(arc_size(&app), 180.0, "two turns of half a line each"); + + // Within one touchpad gesture, a pause of half a second keeps the half line from before it. + let phased = |phase| match half.clone() { + Event::MouseWheel { unit, delta, modifiers, source, .. } => Event::MouseWheel { unit, delta, phase, modifiers, source }, + e => e, + }; + // The Start event's motion does not count, as for egui's scroll. + frame_at(&mut app, &ctx, vec![phased(egui::TouchPhase::Start), phased(egui::TouchPhase::Move)], Some(200.0)); + assert_eq!(arc_size(&app), 180.0, "a half line and the motion of a Start"); + // Ctrl let go during the gesture still counts until it ends. + let let_go = match phased(egui::TouchPhase::Move) { + Event::MouseWheel { unit, delta, phase, source, .. } => Event::MouseWheel { unit, delta, phase, modifiers: Modifiers::NONE, source }, + e => e, + }; + frame_at(&mut app, &ctx, vec![let_go], Some(200.5)); + assert_eq!(arc_size(&app), 195.0, "one gesture of two half lines"); + // Shift joining the gesture ends what Ctrl held. + let shifted = match phased(egui::TouchPhase::Move) { + Event::MouseWheel { unit, delta, phase, source, .. } => Event::MouseWheel { unit, delta, phase, modifiers: Modifiers::SHIFT, source }, + e => e, + }; + frame_at(&mut app, &ctx, vec![shifted.clone(), shifted], Some(200.6)); + assert_eq!(arc_size(&app), 195.0, "Shift joined the gesture"); + frame_at(&mut app, &ctx, vec![phased(egui::TouchPhase::Move), phased(egui::TouchPhase::Move)], Some(200.7)); + assert_eq!(arc_size(&app), 195.0, "Shift let go stays in the gesture"); + + // A plain wheel turn half a second after the Ctrl one, with no frame in between, scrolls. + let still = view(&app); + let plain = Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: MouseWheelSource::Wheel, + }; + frame_at(&mut app, &ctx, vec![phased(egui::TouchPhase::End)], Some(201.0)); + frame_at(&mut app, &ctx, vec![plain], Some(201.5)); + for k in 1..=40 { + frame_at(&mut app, &ctx, vec![], Some(201.5 + f64::from(k) / 60.0)); + } + assert_eq!(arc_size(&app), 195.0); + assert_ne!(view(&app), still, "the plain turn scrolled"); + + // From a source that is not named a touchpad, the same pause within a gesture ends the turn, + // as egui's scroll timeout does. + let unknown = |phase| match phased(phase) { + Event::MouseWheel { unit, delta, phase, modifiers, .. } => { + Event::MouseWheel { unit, delta, phase, modifiers, source: MouseWheelSource::Unknown } + } + e => e, + }; + frame_at(&mut app, &ctx, vec![Event::PointerMoved(at), unknown(egui::TouchPhase::Start), unknown(egui::TouchPhase::Move)], Some(300.0)); + frame_at(&mut app, &ctx, vec![unknown(egui::TouchPhase::Move)], Some(300.5)); + assert_eq!(arc_size(&app), 195.0, "two turns of half a line each from an unnamed source"); +} + +/// A mouse wheel that reports its notches in points (as a browser does) steps once per notch, +/// however many points a notch is. Under a modal dialog, and for the rest of a turn begun under it, +/// Ctrl+wheel leaves the arc size. +#[test] +fn ctrl_wheel_steps_per_notch_and_not_under_a_dialog() { + let mut app = app(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + turn(&mut app, &ctx, MouseWheelUnit::Point, 100.0, ctrl, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 195.0, "one notch of 100 points"); + turn(&mut app, &ctx, MouseWheelUnit::Point, -3.0, ctrl, MouseWheelSource::Wheel); + assert_eq!(arc_size(&app), 180.0, "one notch of 3 points"); + // On the desktop, point motion from an unknown source is a touchpad's: it steps once per wheel + // line, and smaller motion adds up within the turn. + let line = ctx.options(|o| o.input_options.line_scroll_speed); + turn(&mut app, &ctx, MouseWheelUnit::Point, 2.5 * line, ctrl, MouseWheelSource::Unknown); + assert_eq!(arc_size(&app), 210.0, "two and a half lines"); + turn(&mut app, &ctx, MouseWheelUnit::Point, -line, ctrl, MouseWheelSource::Unknown); + assert_eq!(arc_size(&app), 195.0, "the half line left over did not count in a later turn"); + let small = Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, -line / 4.0), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Unknown, + }; + let at = app.canvas_rect.unwrap().center(); + frame(&mut app, &ctx, vec![Event::PointerMoved(at), small.clone(), small.clone(), small.clone()]); + assert_eq!(arc_size(&app), 195.0, "three quarters of a line"); + frame(&mut app, &ctx, vec![small]); + assert_eq!(arc_size(&app), 180.0, "a whole line"); + for _ in 0..40 { + frame(&mut app, &ctx, vec![]); + } + + let notch = Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Wheel, + }; + app.ui.dialog = Some(crate::state::Dialog::new("preferences", json!({}))); + frame_at(&mut app, &ctx, vec![Event::PointerMoved(at), notch.clone()], Some(300.0)); + assert_eq!(arc_size(&app), 180.0, "under the dialog"); + app.ui.dialog = None; + frame_at(&mut app, &ctx, vec![notch], Some(300.05)); + assert_eq!(arc_size(&app), 180.0, "the rest of a turn begun under the dialog"); +} + +/// With another tool, Ctrl+wheel leaves the Quick Pen's arc size and moves the view as before. +#[test] +fn ctrl_wheel_with_another_tool_moves_the_view() { + let mut app = app(); + app.select_tool("pen"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let still = view(&app); + turn(&mut app, &ctx, MouseWheelUnit::Line, 1.0, Modifiers { ctrl: true, command: true, ..Modifiers::NONE }, MouseWheelSource::Wheel); + assert_eq!(app.session.tool_options_of("quickPen")["turn"], json!(180.0)); + assert_ne!(view(&app), still); +} + +/// The arc size commands step the size by 15° within 1° to 359°, return false at the ends and with +/// another tool, and change the last sharp-corner arc of the path being drawn. +#[test] +fn the_arc_size_commands_step_within_the_range() { + let mut app = app(); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(arc_size(&app), 195.0); + assert_eq!(app.run("tool.quickPen.arcSmaller", json!({})).unwrap(), json!(true)); + for _ in 0..10 { + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + } + assert_eq!(arc_size(&app), 330.0); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(true)); + assert_eq!(app.run("tool.quickPen.arcLarger", json!({})).unwrap(), json!(false), "360° is past 359°"); + assert_eq!(arc_size(&app), 345.0); + + click_doc(&mut app, 100.0, 150.0); + click_doc(&mut app, 200.0, 150.0); + let drawn = paths(&app)[0].clone(); + let undo = app.session.active().unwrap().history.undo.len(); + assert_eq!(app.run("tool.quickPen.arcSmaller", json!({})).unwrap(), json!(true)); + assert_ne!(paths(&app)[0], drawn); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + + app.select_tool("pen"); + assert_eq!(app.run("tool.quickPen.arcSmaller", json!({})).unwrap(), json!(false)); + assert_eq!(app.session.tool_options_of("quickPen")["turn"], json!(330.0)); +} diff --git a/docs/mcp.md b/docs/mcp.md index ae119cc4b1..850fc50cd1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7303,16 +7303,25 @@ path's last point, drawn with the tool's `action` option: Alt (Option on macOS) pressed and let go with no other key, click or wheel turn in between switches to the next action: Line, Continuous Arc, Sharp Corner Arc, and back to Line. C flips the last piece, while it is a sharp-corner arc, to the other side of its chord. `[` and `]` make the arc size 15° smaller or larger, for the last sharp-corner arc and the -arcs after it. During a drag, C and `[` `]` change the sharp-corner arc being dragged, and Alt switches its action. A -dragged piece ends where the press is let go. A click on the first point closes the path, and a click on an end of an -open path goes on drawing from that end. Escape or Enter ends the path, and so does an edit made to it by another -command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit +arcs after it, as `tool.quickPen.arcSmaller {}` and `tool.quickPen.arcLarger {}` do (each first finishes any pending +tool edit, then returns false, changing nothing more, when the Quick Pen tool is not active or the step would leave 1° to +359°). `tool.quickPen.arcSmaller` and `tool.quickPen.arcLarger` run in the desktop app (`--connect`). Ctrl with a +scroll on a touchpad over the canvas (the Control key on macOS too) changes the arc size as well, as +[Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) +lists: the touchpad makes one step for each wheel line of its motion, and motion that goes on after the fingers lift +makes none. A mouse wheel turned with Ctrl over the canvas does the same, one step for each wheel event (one per +notch). Up makes the arc size larger and down smaller, sideways motion makes no step, and the view does not zoom or +scroll for the rest of that wheel turn. During a drag, C, `[` `]` and the wheel change the sharp-corner arc being +dragged, and Alt switches its action. A dragged piece ends where the press is let go. A click on the first point +closes the path, and a click on an end of an open path goes on drawing from that end. Escape or Enter ends the path, +and so does an edit made to it by another command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit stays, and the piece stays as last shown. With the `realTimeDrawing` preference off, a press during which another command edits the document adds no piece, and the edit stays. The path's points show as circles without handles, and a preview shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step, together with the flips and size changes made during its drag, and each flip or size change made between presses is one undo step. The -arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` do during a drag and Enter ending the -path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences +arc size of 180°, its 15° steps, the side an arc bulges to, what C, `[` `]` and the wheel do during a drag, Enter +ending the path, the mouse wheel changing the arc size, and the wheel's step per event or wheel line and its direction are +VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0616b700f0..9734e21c74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -633,7 +633,7 @@ since 2026-10-01. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. -- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. +- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` and Ctrl with a touchpad scroll or a mouse wheel over the canvas change the arc size by 15° (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`), a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, C, `[` and `]` changing the arc being dragged, the mouse wheel changing the arc size, and one step per wheel event of a mouse wheel are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `tests::quickpenwheel`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7d1d61416e..3acd3960a2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -205,7 +205,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` and Ctrl+scroll for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; Ctrl+scroll on a touchpad, and VectorCraft's own Ctrl+mouse wheel, over the canvas for the arc size in `crates/ui-egui/src/canvas/quick_pen_wheel.rs` (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`). Not yet: dragging a path's ends to change a line's or arc's length, and editing and deleting with the tool | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | From e799a697703c3c1883c82a0094f56812cd6d7ba5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Thu, 19 Nov 2026 20:12:18 -0800 Subject: [PATCH 11/71] Quick Pen: Ctrl+wheel steps the arc size in event order Each wheel event's whole steps now run before the next event's, and only the fraction of a wheel line carries over. A notch up refused at 345 degrees no longer cancels a notch down in the same frame, so the size goes to 330, and a touchpad gesture that starts later in a frame keeps the steps of the motion before it. A frame whose Ctrl+wheel event stepped the arc size no longer moves the view when a later event in the same frame starts a new turn. --- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 43 +++++++++----- crates/ui-egui/src/tests/quickpenwheel.rs | 59 ++++++++++++++++++++ 2 files changed, 88 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs index 6ba86ca852..129e234ee4 100644 --- a/crates/ui-egui/src/canvas/quick_pen_wheel.rs +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -32,7 +32,7 @@ struct ArcWheel { const TURN_GAP: f64 = 0.150; const GESTURE_GAP: f64 = 1.0; -/// Most steps one frame makes: from 1° to 359° is fewer than 24 steps of 15°. +/// Most steps one wheel event makes: from 1° to 359° is fewer than 24 steps of 15°. const MOST_STEPS: i32 = 24; /// Ctrl alone (the Control key on macOS too). @@ -51,6 +51,11 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, over: bool) -> bool { let line = ui.ctx().options(|o| o.input_options.line_scroll_speed).max(1.0); let takes = over && app.session.tool_id() == vectorcraft_tools::quickpen::ID; let mut now = before; + // The steps to make, in event order: the command and how many times to run it. + let mut runs: Vec<(&str, i32)> = Vec::new(); + // Whether the tool took any of this frame's wheel events, even one of a turn that a later event + // of the frame ended: the view does not move for this frame's events then. + let mut took = false; let (any, scrolling) = ui.input(|i| { let mut any = false; for e in &i.events { @@ -80,6 +85,7 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, over: bool) -> bool { continue; } now.taken = true; + took = true; // Only Move events move, as egui's scroll; momentum after the fingers lift makes no step. if *phase != egui::TouchPhase::Move || *source == egui::MouseWheelSource::Momentum { continue; @@ -96,8 +102,18 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, over: bool) -> bool { } else { s }; - if d.is_finite() { - now.rest += d; + if !d.is_finite() { + continue; + } + // Each event's whole steps are made before the next event's, in the order the events + // came, so a step refused at an end of the range does not cancel a later step back; only + // the fraction of a wheel line is left for later motion. + now.rest += d; + let whole = now.rest.trunc(); + now.rest -= whole; + if whole != 0.0 { + let cmd = if whole > 0.0 { "tool.quickPen.arcLarger" } else { "tool.quickPen.arcSmaller" }; + runs.push((cmd, (whole.abs().min(MOST_STEPS as f32)) as i32)); } } (any, i.is_scrolling()) @@ -105,21 +121,20 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, over: bool) -> bool { if !any && !scrolling { now = ArcWheel::default(); } - let steps = now.rest.trunc(); - now.rest -= steps; - let (cmd, n) = if steps > 0.0 { ("tool.quickPen.arcLarger", steps) } else { ("tool.quickPen.arcSmaller", -steps) }; - for _ in 0..(n as i32).min(MOST_STEPS) { - match app.run(cmd, json!({})) { - Ok(serde_json::Value::Bool(true)) => {} - Ok(_) => break, - Err(e) => { - app.ui.status = e; - break; + 'runs: for (cmd, n) in runs { + for _ in 0..n { + match app.run(cmd, json!({})) { + Ok(serde_json::Value::Bool(true)) => {} + Ok(_) => break, + Err(e) => { + app.ui.status = e; + break 'runs; + } } } } if now != before { ui.data_mut(|d| d.insert_temp(id, now)); } - now.taken + now.taken || took } diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs index 597035bc47..edf6940edb 100644 --- a/crates/ui-egui/src/tests/quickpenwheel.rs +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -363,6 +363,65 @@ fn ctrl_wheel_steps_per_notch_and_not_under_a_dialog() { assert_eq!(arc_size(&app), 180.0, "the rest of a turn begun under the dialog"); } +/// Wheel events in one frame step in the order they came: a notch up refused at the top of the +/// range does not cancel the notch down after it, and a touchpad gesture that starts later in the +/// frame keeps the steps of the motion before it and does not let that motion move the view. +#[test] +fn ctrl_wheel_steps_in_event_order() { + let mut app = app(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + app.run("tool.setOption", json!({"key": "turn", "value": 345})).unwrap(); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let at = app.canvas_rect.unwrap().center(); + let notch = |dy: f32| Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Wheel, + }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), notch(1.0), notch(-1.0)]); + assert_eq!(arc_size(&app), 330.0, "up refused at 345°, then down"); + for _ in 0..40 { + frame(&mut app, &ctx, vec![]); + } + + let line = ctx.options(|o| o.input_options.line_scroll_speed); + let pad = |phase, dy: f32| Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, dy), + phase, + modifiers: ctrl, + source: MouseWheelSource::Trackpad, + }; + frame_at( + &mut app, + &ctx, + vec![pad(egui::TouchPhase::Start, 0.0), pad(egui::TouchPhase::Move, -line), pad(egui::TouchPhase::Start, 0.0)], + Some(500.0), + ); + assert_eq!(arc_size(&app), 315.0, "a line down before a later Start"); + for k in 1..=40 { + frame_at(&mut app, &ctx, vec![], Some(500.0 + f64::from(k) / 60.0)); + } + + // A Ctrl notch followed in the same frame by the Start of a touchpad gesture without Ctrl: the + // notch steps the arc size and does not move the view. + let still = view(&app); + let plain_start = Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, 0.0), + phase: egui::TouchPhase::Start, + modifiers: Modifiers::NONE, + source: MouseWheelSource::Trackpad, + }; + frame_at(&mut app, &ctx, vec![Event::PointerMoved(at), notch(1.0), plain_start], Some(600.0)); + assert_eq!(arc_size(&app), 330.0); + assert_eq!(view(&app), still, "the notch did not move the view"); +} + /// With another tool, Ctrl+wheel leaves the Quick Pen's arc size and moves the view as before. #[test] fn ctrl_wheel_with_another_tool_moves_the_view() { From c4df0b626fb7520e64b39cb82473c86a214517e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 22 Nov 2026 13:34:17 -0800 Subject: [PATCH 12/71] Quick Pen: keys tapped between touchpad wheel events count for the gesture During a touchpad gesture the held modifiers were taken only from wheel events, so Shift pressed and let go between two of them did not count and the next Ctrl-only event still stepped the arc size. While a gesture is under way, the modifiers of key events and modifier changes now join the gesture's held set in the order they come. The mouse-wheel path is unchanged. --- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 8 +++ crates/ui-egui/src/tests/quickpenwheel.rs | 51 ++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs index 129e234ee4..8b036ada5d 100644 --- a/crates/ui-egui/src/canvas/quick_pen_wheel.rs +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -59,6 +59,14 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, over: bool) -> bool { let (any, scrolling) = ui.input(|i| { let mut any = false; for e in &i.events { + // Keys pressed or let go between a touchpad gesture's wheel events count for the rest of + // the gesture too, in the order they came. + if let egui::Event::ModifiersChanged(m) | egui::Event::Key { modifiers: m, .. } = e { + if now.gesture { + now.held |= *m; + } + continue; + } let egui::Event::MouseWheel { unit, delta, phase, modifiers, source } = e else { continue }; any = true; // A wheel event after egui's scroll timeout, or a touchpad gesture's start, begins a diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs index edf6940edb..4e5800c269 100644 --- a/crates/ui-egui/src/tests/quickpenwheel.rs +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -422,6 +422,57 @@ fn ctrl_wheel_steps_in_event_order() { assert_eq!(view(&app), still, "the notch did not move the view"); } +/// Shift pressed and let go between two wheel events of a touchpad gesture held with Ctrl counts for +/// the rest of the gesture, whether it comes as a key event or as a change of the held modifiers. +/// Between a mouse wheel's notches it does not. +#[test] +fn shift_tapped_between_touchpad_wheel_events_counts_for_the_gesture() { + let mut app = app(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let both = Modifiers { shift: true, ..ctrl }; + let at = app.canvas_rect.unwrap().center(); + let line = ctx.options(|o| o.input_options.line_scroll_speed); + let pad = |phase, dy: f32| Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, dy), + phase, + modifiers: ctrl, + source: MouseWheelSource::Trackpad, + }; + let shift_key = |pressed, modifiers| Event::Key { key: egui::Key::ShiftLeft, physical_key: None, pressed, repeat: false, modifiers }; + let taps = [vec![shift_key(true, both), shift_key(false, ctrl)], vec![Event::ModifiersChanged(both), Event::ModifiersChanged(ctrl)]]; + let mut t = 700.0; + for tap in taps { + let size = arc_size(&app); + frame_at(&mut app, &ctx, vec![Event::PointerMoved(at), pad(egui::TouchPhase::Start, 0.0), pad(egui::TouchPhase::Move, line)], Some(t)); + assert_eq!(arc_size(&app), size + 15.0, "a line up with Ctrl"); + frame_at(&mut app, &ctx, tap.clone(), Some(t + 0.1)); + frame_at(&mut app, &ctx, vec![pad(egui::TouchPhase::Move, line)], Some(t + 0.2)); + assert_eq!(arc_size(&app), size + 15.0, "Shift tapped mid-gesture: {tap:?}"); + frame_at(&mut app, &ctx, vec![pad(egui::TouchPhase::End, 0.0)], Some(t + 0.3)); + for k in 1..=40 { + frame_at(&mut app, &ctx, vec![], Some(t + 0.3 + f64::from(k) / 60.0)); + } + t += 100.0; + } + + let size = arc_size(&app); + let notch = Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: ctrl, + source: MouseWheelSource::Wheel, + }; + frame_at(&mut app, &ctx, vec![Event::PointerMoved(at), notch.clone()], Some(t)); + frame_at(&mut app, &ctx, vec![shift_key(true, both), shift_key(false, ctrl)], Some(t + 0.05)); + frame_at(&mut app, &ctx, vec![notch], Some(t + 0.1)); + assert_eq!(arc_size(&app), size + 30.0, "two Ctrl notches around a Shift tap"); +} + /// With another tool, Ctrl+wheel leaves the Quick Pen's arc size and moves the view as before. #[test] fn ctrl_wheel_with_another_tool_moves_the_view() { From 1807f9ef3773eb6c8c11b34dfbac149f490a1315 Mon Sep 17 00:00:00 2001 From: tareq <tareq.halaby@gmail.com> Date: Tue, 24 Nov 2026 09:38:51 +0100 Subject: [PATCH 13/71] feat(i18n): add Arabic language support, catalog and 6-form plural rules --- crates/ui-egui/src/i18n.rs | 1 + crates/ui-egui/src/i18n/ar.tsv | 888 +++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tests.rs | 34 +- docs/localization-parity.md | 5 +- 4 files changed, 924 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/i18n/ar.tsv diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index ec1296192f..1900d249aa 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -69,6 +69,7 @@ static EMBEDDED: &Embedded = &[ ("fi", "", include_str!("i18n/fi.tsv")), ("tr", "", include_str!("i18n/tr.tsv")), ("ca", "", include_str!("i18n/ca.tsv")), + ("ar", "", include_str!("i18n/ar.tsv")), ]; /// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv new file mode 100644 index 0000000000..353f6dd5b9 --- /dev/null +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -0,0 +1,888 @@ +# Arabic (ar) catalog. Same format as zh-hant.tsv: context <TAB> source <TAB> translation +# (empty context = a plain UI string; `@id` = a command id; `@plural` = 6 CLDR forms; +# `@msg` = a status or error message). +# +# Clean-room: written from the meaning of VectorCraft's English labels in Modern Standard Arabic, +# using ordinary vector-illustration vocabulary (لوحة عمل، مسار، نقطة إرساء، حد، +# تعبئة، عينة لون، تدرج، قناع، طبقة). No other application's Arabic localisation +# resource, string table or product UI was consulted or copied; add entries the same way. +# +# Conventions: labels use standard Arabic creative suite terminology. Plural rule (CLDR): +# zero|one|two|few|many|other. Status and error messages (`@msg`) keep the case of their English +# first word. Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name +# (VectorCraft), OpenType, the built-in workspace names and perspective grid presets. +# Every `ar-*` locale (ar-SA, ar-EG, ar-AE, ar-MA, ar-KW, etc.) resolves here. Keep the +# placeholders ({name}), trailing "…" and leading/trailing spaces of fragments exactly as they are. +@id language.name العربية + % of all commits % من كل الإيداعات + 16 bit 16 بت + 24 bits/pixel 24 بت/بكسل + 32 bits/pixel 32 بت/بكسل + 8 bit 8 بت + About حول + Absolute مطلق + Absolute Colorimetric قياس لوني مطلق + Actions الإجراءات + Activate Panel تنشيط اللوحة + Actual Size الحجم الفعلي + Adaptive تكيفي + Add إضافة + Add Anchor Point إضافة نقطة إرساء + Add Anchor Point Tool أداة إضافة نقطة ارتكاز + Add Anchor Points إضافة نقاط إرساء + Add to Swatches إضافة إلى عينات الألوان + Advanced متقدم + Align محاذاة + All الكل + All Caps جميع الأحرف كبيرة + All Layers كل الطبقات + All Slices كل الشرائح + Alt Alt + Amount المقدار + Amount: المقدار: + Anchor Point نقطة إرساء + Angle الزاوية + Angle: الزاوية: + Anti-alias إزالة التسنن + Anti-Alias إزالة التسنن + Appearance المظهر + Appearance of Black مظهر اللون الأسود + Apply تطبيق + Arc قوس + Arrange ترتيب + Art & Illustration الفن والرسم التوضيحي + Artboard لوح التصميم + Artboard Tool أداة لوحة العمل + Artboards لوحات العمل + ArtCraft Website موقع ArtCraft + ArtCraft website موقع ArtCraft + Aspect Ratio نسبة العرض إلى الارتفاع + Assign Profile… تعيين ملف تعريف… + Attributes السمات + Author: المؤلف: + Auto تلقائي + Auto Color لون تلقائي + Auto-Collapse Iconic Panels طي الألواح الرمزية تلقائيًا + Automate أتمتة + Automatic تلقائي + Average متوسط + Average… توسيط… + Background Contents محتويات الخلفية + Balance التوازن + Baseline خط الأساس + Baseline Optimized أساسي محسّن + Basic أساسي + Batch… دفعة… + Bend: الانحناء: + Best الأفضل + Bevel مشطوفة + Bicubic ثنائي التكعيب + Binary assets added الأصول الثنائية المضافة + Binary assets removed الأصول الثنائية المحذوفة + Bitmap صورة نقطية + Black أسود + Black & White أبيض وأسود + Blend دمج / مزج + Bloat انتفاخ + Blob Brush فرشاة التلطيخ + Blocks كتل + Blue أزرق + Blur ضبابية + Bold غامق + Bottom أسفل + Bottom Left أسفل اليسار + Bottom Right أسفل اليمين + Bottom: أسفل: + Brightness السطوع + Brightness/Contrast… السطوع/التباين… + Brightness: السطوع: + Bring Forward إحضار للأمام + Bring to Front إحضار إلى المقدمة + Brushes الفرش + Cancel إلغاء + Canvas مساحة الرسم + Cascade تتالي + Cell Size حجم الخلية + Center مركز + Centimeters سنتيمترات + Chalk & Charcoal طباشير وفحم + Change تغيير + Change All تغيير الكل + Change Panel Layout تغيير تخطيط اللوحات + Channel قناة + Character حرف + Character Styles أنماط الأحرف + Charcoal فحم + Check Spelling… تدقيق إملائي… + Chrome كروم + Circle دائرة + Classic كلاسيكي + Clear مسح + Clear All مسح الكل + Clear Guides مسح خطوط الإرشاد + Clear History مسح السجل + Clear Recent Files مسح الملفات الأخيرة + Clipboard Handling معالجة الحافظة + Close إغلاق + Close All إغلاق الكل + Close Panel إغلاق اللوحة + Cmd Cmd + CMYK Color ألوان CMYK + Coarse Dots نقاط خشنة + Collapse Panel Group طي مجموعة اللوحات + Color اللون + Color Burn حرق اللون + Color Dodge تفادي اللون + Color Guide دليل الألوان + Color Halftone… أنصاف ألوان… + Color Management إدارة الألوان + Color Mode وضع الألوان + Color Settings… إعدادات الألوان… + Color Table جدول الألوان + Color: اللون: + Colorize تلوين + Colors الألوان + Command الأمر + Commits الإيداعات + Community المجتمع + Company الشركة + Compound Path مسار مركب + Compression الضغط + Contextual Alternates بدائل سياقية + Contrast التباين + Contributors المساهمون + Conté Crayon قلم Conté + Convert to Shape تحويل إلى شكل + Convert to sRGB تحويل إلى sRGB + Cool بارد + Copy نسخ + Copyright حقوق النشر + Copyright and Contact Info حقوق النشر ومعلومات الاتصال + Copyrighted محمي بحقوق النشر + Corner زاوية + Corners الزوايا + Create إنشاء + Create Clipping Mask إنشاء قناع اقتطاع + Create Gradient Mesh… إنشاء شبكة تدرج… + Create Object Mosaic… إنشاء فسيفساء كائن… + Crop اقتصاص + Cross صليب + Crystallize تبلور + Crystallize… تبلور… + Ctrl Ctrl + Current Colors الألوان الحالية + Curvature الانحناء + Curves… المنحنيات… + Custom مخصص + Cut قص + Cyan سماوي + Dark داكن + Darken تغميق + Dash شرطة + Dashed متقطع + Data Sets مجموعات البيانات + De-Interlace… إزالة التشابك… + Decorative زخرفي + Default افتراضي + Delete حذف + Delete Anchor Point حذف نقطة إرساء + Delete Anchor Point Tool أداة حذف نقطة ارتكاز + Delete Brush حذف الفرشاة + Delete Group حذف المجموعة + Delete Layer حذف الطبقة + Delete Workspace حذف مساحة العمل + Depth العمق + Description الوصف + Deselect إلغاء التحديد + Detail التفاصيل + Devices الأجهزة + Diameter: القطر: + Diamond ماسي + Difference فرق + Diffusion الانتشار + Direct Selection تحديد مباشر + Direct Selection Tool أداة التحديد المباشر + Discord Discord + Discretionary Ligatures حروف مركبة اختيارية + Display name الاسم المعروض + Distance المسافة + Distort تشويه + Distortion التشويه + Distribute توزيع + Dither ترقيش + Divide تقسيم + Dock Panel إرساء اللوحة + Document المستند + Document Color Mode نمط ألوان المستند + Document Info معلومات المستند + Document Setup… إعداد المستند… + Don't Save عدم الحفظ + Done تم + Dots نقاط + Draft مسودة + Drop Shadow ظل مسقط + Drop Shadow… ظل مسقط… + Duplicate تكرار + Duplicate Layer تكرار الطبقة + Duplication تكرار + Edge الحافة + Edge Only الحافة فقط + Edit تحرير + Edit Colors تحرير الألوان + Edit Contents تحرير المحتويات + Effect تأثير + Effects التأثيرات + Eliminate إزالة + Ellipse شكل بيضاوي + Ellipse Tool أداة الشكل البيضاوي + Entire Font الخط بالكامل + Eraser ممحاة + Eraser Tool أداة الممحاة + Error خطأ + Even Fields حقول زوجية + Exact دقيق + Exclude استبعاد + Exclusion استبعاد + Exit خروج + Expand توسيع + Expand Appearance توسيع المظهر + Expand… توسيع… + Export تصدير + Export As… تصدير باسم… + Export for Screens… تصدير للشاشات… + Export Presets تصدير الإعدادات المسبقة + Export… تصدير… + Eyedropper قطارة + Eyedropper Tool أداة القطارة + Feather تلاشي الحواف + Feather… تلاشي الحواف… + File ملف + File Handling معالجة الملفات + File Info… معلومات الملف… + Files الملفات + Fill تعبئة + Fill: التعبئة: + Film & Video الأفلام والفيديو + Filter فلتر + Find بحث + Find and Replace… بحث واستبدال… + Find Next بحث عن التالي + Fine Dots نقاط دقيقة + First الأول + First commit أول إيداع + Fit ملاءمة + Fit All in Window ملاءمة الكل في النافذة + Fit Artboard in Window ملاءمة لوحة العمل مع النافذة + Fit in View ملاءمة في العرض + Fit on Screen ملاءمة للشاشة + Fixed ثابت + Flare توهج + Flatten Transparency… تسطيح الشفافية… + Flip قلب + Flip Horizontal قلب أفقي + Flip Vertical قلب عمودي + Float in Window تعويم في نافذة + Float Panel تعويم اللوحة + Folder المجلد + Font الخط + Font Preview Size حجم معاينة الخط + Format التنسيق + Format Options خيارات التنسيق + Fractions كسور + Free حر + Free Transform تحويل حر + Frequency التردد + Full Document المستند الكامل + Full Screen Mode وضع ملء الشاشة + Fuzziness: التضبيب: + Gamma غاما + Gamut Warning تحذير النطاق اللوني + Gaussian Blur… ضبابية غاوسية… + General عام + Global شامل + Glyphs المحارف + Good جيد + Grab bag مزيج عشوائي + Gradient تدرج + Gradient Tool أداة التدرج + Gradients التدرجات + Grain حبيبات + Grainy Dots نقاط حبيبية + Graphic Pen قلم رسومي + Graphic Styles الأنماط الرسومية + Graphics الرسومات + Gray رمادي + Gray Gamma 2.2 رمادي غاما 2.2 + Grayscale تدرج الرمادي + Green أخضر + Grid الشبكة + Grid Size: حجم الشبكة: + Gridline every خط الشبكة كل + Group تجميع + Group Selection تحديد مجموعة + Group with تجميع مع + Guides خطوط التوجيه + Guides & Grid خطوط الإرشاد والشبكة + Gutter الفاصل بين الأعمدة + Halftone Pattern نقشة أنصاف الألوان + Hand اليد + Hand Tool أداة اليد + Hard صلب + Hard Light ضوء ساطع + Hard Mix مزج صلب + Height الارتفاع + Height: الارتفاع: + Help تعليمات + Hexagon سداسي + Hide إخفاء + Hide Bounding Box إخفاء مربع الإحاطة + Hide Rulers إخفاء المساطر + Hide Transparency Grid إخفاء شبكة الشفافية + High عالٍ + History السجل + History Options… خيارات السجل… + Home الرئيسية + Horizontal أفقي + Hue درجة اللون + Hue/Saturation… درجة اللون/التشبع… + Hyphenate وصل الكلمات + Hyphenation الوصل بالمكspace + Ignore تجاهل + Image صورة + Image Size حجم الصورة + Image Trace تتبع الصورة + Inches بوصات + Info معلومات + Inner Glow… توهج داخلي… + Inside داخل + Install Plug-in… تثبيت مكون إضافي… + Intensity الشدة + Interlaced متشابك + Interpolation الاستيفاء + Intersect تقاطع + Inverse عكس التحديد + Invert عكس + Italic مائل + Join ربط + Join our Discord انضم إلى ديسكورد + Justification الضبط + Keyboard Shortcuts اختصارات لوحة المفاتيح + Keyboard Shortcuts… اختصارات لوحة المفاتيح… + Kind النوع + Knife سكين + Lab Lab + Landscape أفقي + Language اللغة + Language Options خيارات اللغة + Language: اللغة: + Large كبير + Large Tabs علامات تبويب كبيرة + Lasso حبل التحديد + Lasso Tool أداة الحبل + Last الأخير + Last commit آخر إيداع + Layer طبقة + Layers الطبقات + Layers Panel Options خيارات لوحة الطبقات + Leading تباعد الأسطر + Left يسار + Left-to-Right Paragraph Direction اتجاه الفقرة من اليسار إلى اليمين + Left: يسار: + Legal Legal + Length الطول + Length: الطول: + Letter Letter + Levels المستويات + Levels… المستويات… + Libraries المكتبات + Light فاتح + Light Blue أزرق فاتح + Light Direction اتجاه الضوء + Light Gray رمادي فاتح + Lighten تفتيح + Lighting الإضاءة + Lightness الإضاءة + Lights المناطق الفاتحة + Line خط + Line delta صافي الأسطر + Line Segment قطعة مستقيمة + Linear خطي + Linear Gradient تدرج خطي + Lines خطوط + Lines +/− الأسطر +/− + Lines added الأسطر المضافة + Lines deleted الأسطر المحذوفة + Links الارتباطات + Live Paint Bucket دلو التلوين الحي + Location الموقع + Location: الموقع: + Lock قفل + Lock Guides قفل خطوط الإرشاد + Lock Slices قفل الشرائح + Long Lines خطوط طويلة + Long Strokes ضربات طويلة + Low منخفض + Luminosity السطوع + Magenta أرجواني + Magic Wand العصا السحرية + Magic Wand Tool أداة العصا السحرية + Make الشركة المصنعة + Make Clipping Mask إنشاء قناع قطع + Make Compound Path إنشاء مسار مركب + Make Guides إنشاء خطوط إرشاد + Mask قناع + Matte لون الحافة + Maximize تكبير + Maximum الحد الأقصى + Measure قياس + Medium متوسط + Medium Dots نقاط متوسطة + Medium Lines خطوط متوسطة + Medium Strokes ضربات متوسطة + Merge دمج + Merge Layers دمج الطبقات + Merged PRs طلبات السحب المدمجة + Mesh شبكة + Message: الرسالة: + Method الطريقة + Mezzotint… ميزوتينت… + Millimeters مليمترات + Minimize تصغير + Minimum الحد الأدنى + Minus Back طرح الخلفية + Minus Front طرح المقدمة + Mirror مرآة + Miter حادة + Mobile الجوال + Mode الوضع + Mode: الوضع: + Model الطراز + Models النماذج + Modern حديث + Modify تعديل + Monitor RGB RGB الشاشة + Monochromatic أحادي اللون + Monochrome أحادي اللون + Move تحريك + Move Down تحريك لأسفل + Move Panel تحريك اللوحة + Move Up تحريك لأعلى + Multiply مضاعفة + Name الاسم + Name (A–Z) الاسم (أ–ي) + Name: الاسم: + Navigator الملاح + New جديد + New Group مجموعة جديدة + New Group… مجموعة جديدة… + New Layer… طبقة جديدة… + New Set… مجموعة جديدة… + New Swatch… عينة لون جديدة… + New Workspace مساحة عمل جديدة + New Workspace… مساحة عمل جديدة… + New… جديد… + No contributor data was built into this copy. لم يتم تضمين بيانات المساهمين في هذه النسخة. + No Dither بلا ترقيش + No document لا يوجد مستند + No document open لا يوجد مستند مفتوح + No model credits were built into this copy. لم يتم تضمين بيانات الإشادة بالنماذج في هذه النسخة. + Noise تشويش + None بلا + Normal عادي + Note Paper ورق ملاحظات + NTSC Colors ألوان NTSC + Object كائن + Odd Fields حقول فردية + Off إيقاف + Offset إزاحة + OK موافق + Only Web Colors ألوان الويب فقط + Opacity العتامة + Opacity: العتامة: + Open فتح + Open Documents As Tabs فتح المستندات كعلامات تبويب + Open… فتح… + Optimized محسّن + Options الخيارات + Options… خيارات… + Orange برتقالي + Ordinals أرقام ترتيبية + Orientation الاتجاه + Original الأصلي + Other أخرى + Outer Glow… توهج خارجي… + Outline مخطط تفصيلي + Outline Stroke تحديد مسار الحد + Output الإخراج + Output: الإخراج: + Outside خارج + Overlay تراكب + Overlay Edge تراكب الحافة + Overprint طباعة فوقية + Overprint Preview معاينة الطباعة الفوقية + Package… تجميع الحزمة… + Paintbrush فرشاة الطلاء + Panel menu قائمة اللوحة + Panel Options… خيارات اللوحة… + Panels اللوحات + Paragraph فقرة + Paragraph Styles أنماط الفقرات + Paste لصق + Paste in Back لصق في الخلف + Paste in Front لصق في المقدمة + Paste in Place لصق في المكان + Paste on All Artboards لصق على كافة لوحات العمل + Path مسار + Path Eraser ممحاة المسار + Pathfinder مستكشف المسارات + Paths المسارات + Pattern النقشة + Pen القلم + Pen Tool أداة القلم + Pencil قلم رصاص + Pencil Tool أداة القلم الرصاص + Perceptual إدراكي + Performance الأداء + Perspective منظور + Perspective Grid شبكة المنظور + Photocopy نسخ ضوئي + Picas بيكا + Pixel بكسل + Pixel Preview معاينة البكسل + Pixelate بكسلة + Pixels بكسل + Place… إدراج… + Plaster جبس + Plug-ins المكونات الإضافية + Plug-ins & Scratch Disks المكونات الإضافية وأقراص العمل المؤقتة + Point Sample عينة نقطية + Pointillize… تنقيط… + Points نقاط + Polar Grid شبكة قطبية + Polygon مضلع + Polygon Tool أداة المضلع + Portrait عمودي + Position الموضع + Postcard بطاقة بريدية + Preferences التفضيلات + Preserve الاحتفاظ + PRESET DETAILS تفاصيل الإعداد المسبق + Preset Name اسم الإعداد المسبق + Preset: الإعداد المسبق: + Presets إعدادات مسبقة + Presets: الإعدادات المسبقة: + Press keys… اضغط المفاتيح… + Pressure الضغط + Preview معاينة + Print طباعة + Print Tiling تجانب الطباعة + Printer الطابعة + Print… طباعة… + Progressive تدريجي + Proof Colors ألوان المعاينة الطباعية + Proof Setup إعداد المعاينة الطباعية + Properties الخصائص + Public Domain ملكية عامة + Pucker انكماش + Punctuation علامات الترقيم + Puppet Warp التواء الدمية + Purple بنفسجي + Quality الجودة + Quick Actions إجراءات سريعة + Quickly start a new file بدء ملف جديد بسرعة + Radial شعاعي + Radial Blur… ضبابية شعاعية… + Radial Gradient تدرج شعاعي + Radius نصف القطر + Radius: نصف القطر: + Random عشوائي + Range: النطاق: + Rasterize تنقيط + Rasterize… تنقيط… + Ratio النسبة + Real name الاسم الحقيقي + Rearrange All Artboards… إعادة ترتيب كافة لوحات العمل… + Recent الأخيرة + Recent Files الملفات الأخيرة + Recolor Artwork… إعادة تلوين العمل الفني… + Rectangle مستطيل + Rectangle Tool أداة المستطيل + Rectangular Grid شبكة مستطيلة + Red أحمر + Redo إعادة + Reflect انعكاس + Regular عادي + Relative نسبي + Relative Colorimetric قياس لوني نسبي + Release Clipping Mask تحرير قناع القطع + Release Compound Path تحرير المسار المركب + Release Guides تحرير خطوط الإرشاد + Remove إزالة + Remove Anchor Points إزالة نقاط الإرساء + Rename إعادة تسمية + Rename Group… إعادة تسمية المجموعة… + Rename… إعادة تسمية… + Repeat تكرار + Replace استبدال + Reselect إعادة التحديد + Reset إعادة تعيين + Reset Preferences إعادة تعيين التفضيلات + Reset to Default إعادة تعيين إلى الافتراضي + Reshape إعادة تشكيل + Resize panel window تغيير حجم نافذة اللوحة + Resize panels تغيير حجم اللوحات + Resolution: الدقة: + Restore استعادة + Reticulation تشبيك + Reverse Path Direction عكس اتجاه المسار + Reverse the order عكس الترتيب + Revert استعادة + RGB Color ألوان RGB + Right يمين + Right-to-Left Paragraph Direction اتجاه الفقرة من اليمين إلى اليسار + Right: يمين: + Roman روماني + Rotate تدوير + Rotate View تدوير العرض + Rotate View Tool أداة تدوير العرض + Rotation تدوير + Round مستديرة + Rounded Rectangle مستطيل مستدير الزوايا + Roundness: الاستدارة: + Rulers المساطر + Rulers & Grids المساطر والشبكات + Saturate زيادة التشبع + Saturation التشبع + Save حفظ + Save a Copy… حفظ نسخة… + Save As… حفظ باسم… + Save for Web (Legacy)… حفظ للويب (قديم)… + Save Preset… حفظ الإعداد المسبق… + Save Selection حفظ التحديد + Save Selection… حفظ التحديد… + Saved تم الحفظ + Save… حفظ… + Scale تحجيم + Scale Cursor Proportional to UI تحجيم المؤشر بالتناسب مع واجهة المستخدم + Scale: المقياس: + Scallop تسنن + Scatter تبعثر + Scissors مقص + Scratch Disks أقراص التخزين المؤقت + Screen شاشة + Screen Mode وضع الشاشة + Scripts البرامج النصية + Search بحث + Select تحديد + Select All تحديد الكل + Select: التحديد: + Selection تحديد + Selection & Anchor Display التحديد وعرض نقاط الإرساء + Selective انتقائي + Send Backward إرسال للخلف + Send to Back إرسال إلى المؤخرة + Set: المجموعة: + Settings… إعدادات… + Shape شكل + Shape Builder منشئ الأشكال + Shape: الشكل: + Shapes الأشكال + Sharpen زيادة الحدة + Shear إمالة + Shear… قص مائل… + Shift Shift + Short Lines خطوط قصيرة + Short Strokes ضربات قصيرة + Show إظهار + Show All إظهار الكل + Show Bounding Box إظهار مربع الإحاطة + Show Grid إظهار الشبكة + Show Guides إظهار خطوط الإرشاد + Show in Folder إظهار في المجلد + Show Mesh إظهار الشبكة + Show Rulers إظهار المساطر + Show Tool Group Labels إظهار تسميات مجموعات الأدوات + Show Transparency Grid إظهار شبكة الشفافية + Show: إظهار: + Sides: الأضلاع: + Simplify… تبسيط… + Simulate Paper محاكاة الورق + Size الحجم + Size: الحجم: + Skew إمالة + Slice Options… خيارات الشريحة… + Slice Tool أداة الشريحة + Slices الشرائح + Small صغير + Small Caps أحرف استهلالية صغيرة + Smaller ↔ Larger أصغر ↔ أكبر + Smart Blur… ضبابية ذكية… + Smart Guides خطوط الإرشاد الذكية + Smooth تنعيم + Snap to Grid محاذاة إلى الشبكة + Soft ناعم + Soft Light ضوء خافت + Softness النعومة + Solid مصمت + Sort فرز + Spacing التباعد + Spin دوران + Spiral حلزون + Sponge إسفنجة + Spot Color لون موضعي + Square مربع + Stamp ختم + Standard قياسي + Standard Ligatures حروف مركبة قياسية + Star نجمة + Step Backward خطوة للخلف + Step Forward خطوة للأمام + Stop إيقاف + Strength القوة + Strikethrough يتوسطه خط + Stroke الحد + Patterns النقشات + Stroke Options خيارات الحدود + Stroke: حدود: + Style النمط + Stylize تنميط + Subdivisions التقسيمات الفرعية + Subtract طرح + Swash حروف مزخرفة + Swatches عينات الألوان + Symbol Sprayer بخاخ الرموز + Symbols الرموز + System Title Bar شريط عنوان النظام + Table جدول + Tabloid Tabloid + Taper التناقص التدريجي + Target الهدف + Target: الهدف: + Temperature درجة الحرارة + Texture الملمس + Thickness السماكة + Threshold العتبة + Tile تجانب + Tint صبغة + Tolerance التفاوت + Tolerance: التفاوت: + Tool أداة + Tools الأدوات + Top أعلى + Top Left أعلى اليسار + Top Right أعلى اليمين + Top: أعلى: + Torn Edges حواف ممزقة + Total: الإجمالي: + Tracking تباعد الأحرف + Transform تحويل + Transparency الشفافية + Transparent شفاف + Trap… حصر الألوان… + Triangle مثلث + Trim قص الحواف + Twirl دوامة + Twist لف + Type نوع + Type: النوع: + Type… النص… + UI Scaling تحجيم واجهة المستخدم + Underline تسطير + Undo تراجع + Ungroup فك التجميع + Uniform منتظم + Unite توحيد + Units الوحدات + Unknown غير معروف + Unlock All إلغاء قفل الكل + Unsharp Mask… قناع الحدة… + Untitled بدون عنوان + Use Default استخدام الافتراضي + User Interface واجهة المستخدم + Username اسم المستخدم + Variables المتغيرات + Version الإصدار + Vertical عمودي + Vertical Type Tool أداة النص العمودي + Very High عالٍ جدًا + Video فيديو + View عرض + Violet بنفسجي + Visibility الرؤية + W: العرض: + Warp التواء + Water Paper ورق مائي + Wave… موجة… + Weight الوزن + Weight: السمك: + White أبيض + Width العرض + Width: العرض: + Window نافذة + Windows Windows + Working CMYK مساحة عمل CMYK + Workspace مساحة العمل + Wrinkle تجعد + Yellow أصفر + Zoom تكبير/تصغير + Zoom In تكبير + Zoom Out تصغير + Zoom Tool أداة التكبير/التصغير + “{name}” already exists. Replace it? “{name}” موجود بالفعل. هل تريد استبداله؟ +@plural agrees with {n} default shortcut|agrees with {n} default shortcuts يتطابق مع {n} اختصار افتراضي|يتطابق مع {n} اختصار افتراضي|يتطابق مع {n} اختصارين افتراضيين|يتطابق مع {n} اختصارات افتراضية|يتطابق مع {n} اختصارًا افتراضيًا|يتطابق مع {n} اختصار افتراضي +@plural Color Table ({n} color)|Color Table ({n} colors) جدول الألوان ({n} لون)|جدول الألوان ({n} لون)|جدول الألوان ({n} لونين)|جدول الألوان ({n} ألوان)|جدول الألوان ({n} لونًا)|جدول الألوان ({n} لون) +@plural Delete this {n} graphic style?|Delete these {n} graphic styles? هل تريد حذف هذا النمط الرسومي ({n})؟|هل تريد حذف هذا النمط الرسومي ({n})؟|هل تريد حذف هذين النمطين الرسوميين ({n})؟|هل تريد حذف هذه الأنماط الرسومية ({n})؟|هل تريد حذف هذه الأنماط الرسومية ({n})؟|هل تريد حذف هذه الأنماط الرسومية ({n})؟ +@plural {n} area highlighted|{n} areas highlighted {n} منطقة مميزة|{n} منطقة مميزة|{n} منطقتان مميزتان|{n} مناطق مميزة|{n} منطقةً مميزة|{n} منطقة مميزة +@plural {n} color|{n} colors {n} لون|{n} لون|{n} لونين|{n} ألوان|{n} لونًا|{n} لون +@plural {n} commit|{n} commits {n} إيداع|{n} إيداع|{n} إيداعين|{n} إيداعات|{n} إيداعًا|{n} إيداع +@plural {n} fill|{n} fills {n} تعبئة|{n} تعبئة|{n} تعبئتان|{n} تعبئات|{n} تعبئةً|{n} تعبئة +@plural {n} glyph|{n} glyphs {n} محرف|{n} محرف|{n} محرفين|{n} محارف|{n} محرفًا|{n} محرف +@plural {n} item|{n} items {n} عنصر|{n} عنصر|{n} عنصران|{n} عناصر|{n} عنصرًا|{n} عنصر +@plural {n} Layer|{n} Layers {n} طبقة|{n} طبقة|{n} طبقتان|{n} طبقات|{n} طبقةً|{n} طبقة +@plural {n} more export waiting|{n} more exports waiting {n} عملية تصدير أخرى في الانتظار|{n} عملية تصدير أخرى في الانتظار|{n} عمليتا تصدير أخريان في الانتظار|{n} عمليات تصدير أخرى في الانتظار|{n} عملية تصدير أخرى في الانتظار|{n} عملية تصدير أخرى في الانتظار +@plural {n} object highlighted|{n} objects highlighted {n} كائن مميز|{n} كائن مميز|{n} كائنان مميزان|{n} كائنات مميزة|{n} كائنًا مميزًا|{n} كائن مميز +@plural {n} Object|{n} Objects {n} كائن|{n} كائن|{n} كائنان|{n} كائنات|{n} كائنًا|{n} كائن +@plural {n} part of the file wasn't read|{n} parts of the file weren't read لم يتم قراءة {n} جزء من الملف|لم يتم قراءة {n} جزء من الملف|لم يتم قراءة {n} جزءين من الملف|لم يتم قراءة {n} أجزاء من الملف|لم يتم قراءة {n} جزءًا من الملف|لم يتم قراءة {n} جزء من الملف +@plural {n} PR|{n} PRs {n} طلب سحب|{n} طلب سحب|{n} طلبا سحب|{n} طلبات سحب|{n} طلب سحب|{n} طلب سحب +@plural {n} shortcut is assigned more than once|{n} shortcuts are assigned more than once {n} اختصار تم تعيينه أكثر من مرة|{n} اختصار تم تعيينه أكثر من مرة|{n} اختصاران تم تعيينهما أكثر من مرة|{n} اختصارات تم تعيينها أكثر من مرة|{n} اختصارًا تم تعيينه أكثر من مرة|{n} اختصار تم تعيينه أكثر من مرة +@plural {n} star|{n} stars {n} نجمة|{n} نجمة|{n} نجمتان|{n} نجوم|{n} نجمةً|{n} نجمة +@plural {n} step|{n} steps {n} خطوة|{n} خطوة|{n} خطوتان|{n} خطوات|{n} خطوةً|{n} خطوة +@plural {n} stroke|{n} strokes {n} حد|{n} حد|{n} حدان|{n} حدود|{n} حدًا|{n} حد +3d Bevel مشطوفة +3d Light فاتح +3d Solid مصمت +3d Space Space +@msg Opened {url} تم فتح {url} +axis Both كلاهما +axis Horizontal أفقي +axis Vertical عمودي +effect Horizontal أفقي +effect Points نقاط +effect Regular عادي +effect Soft ناعم +effect Vertical عمودي +gradient-kind Radial شعاعي +imageTrace Outline مخطط تفصيلي +lighting Light فاتح +swatch Aqua أزرق مائي +swatch Black أسود +swatch Blue أزرق +swatch Copper نحاسي +swatch Cyan سماوي +swatch Green أخضر +swatch Indigo نيلي +swatch Magenta أرجواني +swatch Orange برتقالي +swatch Purple بنفسجي +swatch Red أحمر +swatch Violet بنفسجي +swatch White أبيض +swatch Yellow أصفر +theme Appearance المظهر + Gap فجوة + Exposure التعريض + Exposure… التعريض… + Desaturate إزالة التشبع + Adjustment تعديل + Brightness/Contrast السطوع/التباين + Hue/Saturation درجة اللون/التشبع diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 24c452f944..7cb278ade3 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -160,6 +160,36 @@ fn numbered_labels_translate_the_name_before_the_number() { assert_eq!(numbered_label(Lang::EN, "Grays 12"), "Grays 12"); } +#[test] +fn arabic_resolves_locales_and_preferences() { + let ar = Lang::from_code("ar").expect("ar registered"); + assert_eq!(ar.name(), "العربية"); + assert!(ar.complete_menus()); + assert_eq!(Lang::from_pref("ar"), ar); + for tag in ["ar", "AR", "ar-SA", "ar_EG", "ar_EG.UTF-8", "ar-AE", "ar-MA"] { + assert_eq!(i18n().match_tag(tag), Some(ar), "{tag}"); + } + for (en, want) in [ + ("Artboards", "لوحات العمل"), + ("Swatches", "عينات الألوان"), + ("Stroke", "الحد"), + ("Direct Selection", "تحديد مباشر"), + ("Save As…", "حفظ باسم…"), + ("Undo", "تراجع"), + ] { + assert_eq!(tr(ar, en), want, "{en}"); + } +} + +#[test] +fn arabic_plural_rule_has_six_forms() { + let ar = Lang::from_code("ar").expect("ar registered"); + for (n, want) in [(0, "0 إيداع"), (1, "1 إيداع"), (2, "2 إيداعين"), (3, "3 إيداعات"), (11, "11 إيداعًا"), (100, "100 إيداع")] + { + assert_eq!(trn(ar, n, "{n} commit", "{n} commits"), want, "for n={n}"); + } +} + #[test] fn current_language_is_a_frame_setting() { set_current(ZH()); @@ -711,8 +741,8 @@ fn message_dump_lists_the_reported_messages() { } /// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English. -const KEEPS_MENU_NAMES: [&str; 20] = - ["cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca"]; +const KEEPS_MENU_NAMES: [&str; 21] = + ["cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca", "ar"]; /// Menu labels the menu-complete catalogs (Czech, German, Spanish, Italian, Japanese, Brazilian Portuguese) show as they are: the product name, a format name, the built-in workspace /// names and the perspective grid presets (names, shown untranslated wherever else they appear). diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 95ed33bf76..697f3ecf06 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (Arabic (`ar`): catalog added with Modern Standard Arabic menus, preferences, tools, dialogs, commands and 6-form CLDR plurals; native name العربية; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) Per-language status of VectorCraft's interface. How the catalogs work and how to add a language: [`development.md` › Localisation](development.md#localisation). Part of @@ -35,7 +35,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | -| Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | +| Arabic | `ar` | 873 catalog entries: menus, preferences, tools, dialogs, commands and 6-form CLDR plurals; native Arabic name العربية | menus, dialogs, preferences | Arabic: document text has bidi layout and paragraph direction; interface strings render in Modern Standard Arabic via system fallback fonts; full shell mirroring pending STD-I18N-001 | no (AI-drafted, clean-room) | partial | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 7,553 rows, 1,682 of them `@msg` and 49 `@msgplural` (counted 2026-11-15 on `main` at `df984b2a02`): in `COMPLETE_MESSAGES`, and the untranslated report lists 50 missing menu strings, 35 `tl!` literals, 11 undo labels and 1,929 messages for it, the same sets as for Danish; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | @@ -101,6 +101,7 @@ font for the web build. | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | Arabic (`ar`): catalog added with Modern Standard Arabic menus, preferences, tools, dialogs, commands and 6-form CLDR plurals; registered as twenty-sixth non-English language; native name العربية | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) | | 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback and a glyph-coverage filter; status and error messages not yet translated; native review pending | From bce66603c9ffd56985de4974038db61dc26be619 Mon Sep 17 00:00:00 2001 From: tareq <tareq.halaby@gmail.com> Date: Tue, 24 Nov 2026 17:21:31 +0100 Subject: [PATCH 14/71] refactor(i18n): move Arabic catalog to craft-i18n and keep language wiring in app Move the 873 Arabic translated entries to storytold/craft-i18n#486 under AGENTS.md rule 16, keeping the language registration, 6-form CLDR plural routing, and locale preference tests in VectorCraft. --- crates/ui-egui/src/i18n.rs | 2 +- crates/ui-egui/src/i18n/ar.tsv | 884 +------------------------------ crates/ui-egui/src/i18n/tests.rs | 20 +- docs/localization-parity.md | 2 +- 4 files changed, 9 insertions(+), 899 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 1900d249aa..bd6fb2f56c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -142,7 +142,7 @@ impl LangExt for Lang { } fn complete_menus(self) -> bool { - self != Lang::EN + self != Lang::EN && self.code() != "ar" } fn from_code(code: &str) -> Option<Lang> { diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 353f6dd5b9..0920934df4 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -2,887 +2,7 @@ # (empty context = a plain UI string; `@id` = a command id; `@plural` = 6 CLDR forms; # `@msg` = a status or error message). # -# Clean-room: written from the meaning of VectorCraft's English labels in Modern Standard Arabic, -# using ordinary vector-illustration vocabulary (لوحة عمل، مسار، نقطة إرساء، حد، -# تعبئة، عينة لون، تدرج، قناع، طبقة). No other application's Arabic localisation -# resource, string table or product UI was consulted or copied; add entries the same way. -# -# Conventions: labels use standard Arabic creative suite terminology. Plural rule (CLDR): -# zero|one|two|few|many|other. Status and error messages (`@msg`) keep the case of their English -# first word. Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name -# (VectorCraft), OpenType, the built-in workspace names and perspective grid presets. -# Every `ar-*` locale (ar-SA, ar-EG, ar-AE, ar-MA, ar-KW, etc.) resolves here. Keep the -# placeholders ({name}), trailing "…" and leading/trailing spaces of fragments exactly as they are. +# Translations are maintained upstream in storytold/craft-i18n (locales/ar/vectorcraft.tsv) +# under AGENTS.md rule 16. @id language.name العربية - % of all commits % من كل الإيداعات - 16 bit 16 بت - 24 bits/pixel 24 بت/بكسل - 32 bits/pixel 32 بت/بكسل - 8 bit 8 بت - About حول - Absolute مطلق - Absolute Colorimetric قياس لوني مطلق - Actions الإجراءات - Activate Panel تنشيط اللوحة - Actual Size الحجم الفعلي - Adaptive تكيفي - Add إضافة - Add Anchor Point إضافة نقطة إرساء - Add Anchor Point Tool أداة إضافة نقطة ارتكاز - Add Anchor Points إضافة نقاط إرساء - Add to Swatches إضافة إلى عينات الألوان - Advanced متقدم - Align محاذاة - All الكل - All Caps جميع الأحرف كبيرة - All Layers كل الطبقات - All Slices كل الشرائح - Alt Alt - Amount المقدار - Amount: المقدار: - Anchor Point نقطة إرساء - Angle الزاوية - Angle: الزاوية: - Anti-alias إزالة التسنن - Anti-Alias إزالة التسنن - Appearance المظهر - Appearance of Black مظهر اللون الأسود - Apply تطبيق - Arc قوس - Arrange ترتيب - Art & Illustration الفن والرسم التوضيحي - Artboard لوح التصميم - Artboard Tool أداة لوحة العمل - Artboards لوحات العمل - ArtCraft Website موقع ArtCraft - ArtCraft website موقع ArtCraft - Aspect Ratio نسبة العرض إلى الارتفاع - Assign Profile… تعيين ملف تعريف… - Attributes السمات - Author: المؤلف: - Auto تلقائي - Auto Color لون تلقائي - Auto-Collapse Iconic Panels طي الألواح الرمزية تلقائيًا - Automate أتمتة - Automatic تلقائي - Average متوسط - Average… توسيط… - Background Contents محتويات الخلفية - Balance التوازن - Baseline خط الأساس - Baseline Optimized أساسي محسّن - Basic أساسي - Batch… دفعة… - Bend: الانحناء: - Best الأفضل - Bevel مشطوفة - Bicubic ثنائي التكعيب - Binary assets added الأصول الثنائية المضافة - Binary assets removed الأصول الثنائية المحذوفة - Bitmap صورة نقطية - Black أسود - Black & White أبيض وأسود - Blend دمج / مزج - Bloat انتفاخ - Blob Brush فرشاة التلطيخ - Blocks كتل - Blue أزرق - Blur ضبابية - Bold غامق - Bottom أسفل - Bottom Left أسفل اليسار - Bottom Right أسفل اليمين - Bottom: أسفل: - Brightness السطوع - Brightness/Contrast… السطوع/التباين… - Brightness: السطوع: - Bring Forward إحضار للأمام - Bring to Front إحضار إلى المقدمة - Brushes الفرش - Cancel إلغاء - Canvas مساحة الرسم - Cascade تتالي - Cell Size حجم الخلية - Center مركز - Centimeters سنتيمترات - Chalk & Charcoal طباشير وفحم - Change تغيير - Change All تغيير الكل - Change Panel Layout تغيير تخطيط اللوحات - Channel قناة - Character حرف - Character Styles أنماط الأحرف - Charcoal فحم - Check Spelling… تدقيق إملائي… - Chrome كروم - Circle دائرة - Classic كلاسيكي - Clear مسح - Clear All مسح الكل - Clear Guides مسح خطوط الإرشاد - Clear History مسح السجل - Clear Recent Files مسح الملفات الأخيرة - Clipboard Handling معالجة الحافظة - Close إغلاق - Close All إغلاق الكل - Close Panel إغلاق اللوحة - Cmd Cmd - CMYK Color ألوان CMYK - Coarse Dots نقاط خشنة - Collapse Panel Group طي مجموعة اللوحات - Color اللون - Color Burn حرق اللون - Color Dodge تفادي اللون - Color Guide دليل الألوان - Color Halftone… أنصاف ألوان… - Color Management إدارة الألوان - Color Mode وضع الألوان - Color Settings… إعدادات الألوان… - Color Table جدول الألوان - Color: اللون: - Colorize تلوين - Colors الألوان - Command الأمر - Commits الإيداعات - Community المجتمع - Company الشركة - Compound Path مسار مركب - Compression الضغط - Contextual Alternates بدائل سياقية - Contrast التباين - Contributors المساهمون - Conté Crayon قلم Conté - Convert to Shape تحويل إلى شكل - Convert to sRGB تحويل إلى sRGB - Cool بارد - Copy نسخ - Copyright حقوق النشر - Copyright and Contact Info حقوق النشر ومعلومات الاتصال - Copyrighted محمي بحقوق النشر - Corner زاوية - Corners الزوايا - Create إنشاء - Create Clipping Mask إنشاء قناع اقتطاع - Create Gradient Mesh… إنشاء شبكة تدرج… - Create Object Mosaic… إنشاء فسيفساء كائن… - Crop اقتصاص - Cross صليب - Crystallize تبلور - Crystallize… تبلور… - Ctrl Ctrl - Current Colors الألوان الحالية - Curvature الانحناء - Curves… المنحنيات… - Custom مخصص - Cut قص - Cyan سماوي - Dark داكن - Darken تغميق - Dash شرطة - Dashed متقطع - Data Sets مجموعات البيانات - De-Interlace… إزالة التشابك… - Decorative زخرفي - Default افتراضي - Delete حذف - Delete Anchor Point حذف نقطة إرساء - Delete Anchor Point Tool أداة حذف نقطة ارتكاز - Delete Brush حذف الفرشاة - Delete Group حذف المجموعة - Delete Layer حذف الطبقة - Delete Workspace حذف مساحة العمل - Depth العمق - Description الوصف - Deselect إلغاء التحديد - Detail التفاصيل - Devices الأجهزة - Diameter: القطر: - Diamond ماسي - Difference فرق - Diffusion الانتشار - Direct Selection تحديد مباشر - Direct Selection Tool أداة التحديد المباشر - Discord Discord - Discretionary Ligatures حروف مركبة اختيارية - Display name الاسم المعروض - Distance المسافة - Distort تشويه - Distortion التشويه - Distribute توزيع - Dither ترقيش - Divide تقسيم - Dock Panel إرساء اللوحة - Document المستند - Document Color Mode نمط ألوان المستند - Document Info معلومات المستند - Document Setup… إعداد المستند… - Don't Save عدم الحفظ - Done تم - Dots نقاط - Draft مسودة - Drop Shadow ظل مسقط - Drop Shadow… ظل مسقط… - Duplicate تكرار - Duplicate Layer تكرار الطبقة - Duplication تكرار - Edge الحافة - Edge Only الحافة فقط - Edit تحرير - Edit Colors تحرير الألوان - Edit Contents تحرير المحتويات - Effect تأثير - Effects التأثيرات - Eliminate إزالة - Ellipse شكل بيضاوي - Ellipse Tool أداة الشكل البيضاوي - Entire Font الخط بالكامل - Eraser ممحاة - Eraser Tool أداة الممحاة - Error خطأ - Even Fields حقول زوجية - Exact دقيق - Exclude استبعاد - Exclusion استبعاد - Exit خروج - Expand توسيع - Expand Appearance توسيع المظهر - Expand… توسيع… - Export تصدير - Export As… تصدير باسم… - Export for Screens… تصدير للشاشات… - Export Presets تصدير الإعدادات المسبقة - Export… تصدير… - Eyedropper قطارة - Eyedropper Tool أداة القطارة - Feather تلاشي الحواف - Feather… تلاشي الحواف… - File ملف - File Handling معالجة الملفات - File Info… معلومات الملف… - Files الملفات - Fill تعبئة - Fill: التعبئة: - Film & Video الأفلام والفيديو - Filter فلتر - Find بحث - Find and Replace… بحث واستبدال… - Find Next بحث عن التالي - Fine Dots نقاط دقيقة - First الأول - First commit أول إيداع - Fit ملاءمة - Fit All in Window ملاءمة الكل في النافذة - Fit Artboard in Window ملاءمة لوحة العمل مع النافذة - Fit in View ملاءمة في العرض - Fit on Screen ملاءمة للشاشة - Fixed ثابت - Flare توهج - Flatten Transparency… تسطيح الشفافية… - Flip قلب - Flip Horizontal قلب أفقي - Flip Vertical قلب عمودي - Float in Window تعويم في نافذة - Float Panel تعويم اللوحة - Folder المجلد - Font الخط - Font Preview Size حجم معاينة الخط - Format التنسيق - Format Options خيارات التنسيق - Fractions كسور - Free حر - Free Transform تحويل حر - Frequency التردد - Full Document المستند الكامل - Full Screen Mode وضع ملء الشاشة - Fuzziness: التضبيب: - Gamma غاما - Gamut Warning تحذير النطاق اللوني - Gaussian Blur… ضبابية غاوسية… - General عام - Global شامل - Glyphs المحارف - Good جيد - Grab bag مزيج عشوائي - Gradient تدرج - Gradient Tool أداة التدرج - Gradients التدرجات - Grain حبيبات - Grainy Dots نقاط حبيبية - Graphic Pen قلم رسومي - Graphic Styles الأنماط الرسومية - Graphics الرسومات - Gray رمادي - Gray Gamma 2.2 رمادي غاما 2.2 - Grayscale تدرج الرمادي - Green أخضر - Grid الشبكة - Grid Size: حجم الشبكة: - Gridline every خط الشبكة كل - Group تجميع - Group Selection تحديد مجموعة - Group with تجميع مع - Guides خطوط التوجيه - Guides & Grid خطوط الإرشاد والشبكة - Gutter الفاصل بين الأعمدة - Halftone Pattern نقشة أنصاف الألوان - Hand اليد - Hand Tool أداة اليد - Hard صلب - Hard Light ضوء ساطع - Hard Mix مزج صلب - Height الارتفاع - Height: الارتفاع: - Help تعليمات - Hexagon سداسي - Hide إخفاء - Hide Bounding Box إخفاء مربع الإحاطة - Hide Rulers إخفاء المساطر - Hide Transparency Grid إخفاء شبكة الشفافية - High عالٍ - History السجل - History Options… خيارات السجل… - Home الرئيسية - Horizontal أفقي - Hue درجة اللون - Hue/Saturation… درجة اللون/التشبع… - Hyphenate وصل الكلمات - Hyphenation الوصل بالمكspace - Ignore تجاهل - Image صورة - Image Size حجم الصورة - Image Trace تتبع الصورة - Inches بوصات - Info معلومات - Inner Glow… توهج داخلي… - Inside داخل - Install Plug-in… تثبيت مكون إضافي… - Intensity الشدة - Interlaced متشابك - Interpolation الاستيفاء - Intersect تقاطع - Inverse عكس التحديد - Invert عكس - Italic مائل - Join ربط - Join our Discord انضم إلى ديسكورد - Justification الضبط - Keyboard Shortcuts اختصارات لوحة المفاتيح - Keyboard Shortcuts… اختصارات لوحة المفاتيح… - Kind النوع - Knife سكين - Lab Lab - Landscape أفقي - Language اللغة - Language Options خيارات اللغة - Language: اللغة: - Large كبير - Large Tabs علامات تبويب كبيرة - Lasso حبل التحديد - Lasso Tool أداة الحبل - Last الأخير - Last commit آخر إيداع - Layer طبقة - Layers الطبقات - Layers Panel Options خيارات لوحة الطبقات - Leading تباعد الأسطر - Left يسار - Left-to-Right Paragraph Direction اتجاه الفقرة من اليسار إلى اليمين - Left: يسار: - Legal Legal - Length الطول - Length: الطول: - Letter Letter - Levels المستويات - Levels… المستويات… - Libraries المكتبات - Light فاتح - Light Blue أزرق فاتح - Light Direction اتجاه الضوء - Light Gray رمادي فاتح - Lighten تفتيح - Lighting الإضاءة - Lightness الإضاءة - Lights المناطق الفاتحة - Line خط - Line delta صافي الأسطر - Line Segment قطعة مستقيمة - Linear خطي - Linear Gradient تدرج خطي - Lines خطوط - Lines +/− الأسطر +/− - Lines added الأسطر المضافة - Lines deleted الأسطر المحذوفة - Links الارتباطات - Live Paint Bucket دلو التلوين الحي - Location الموقع - Location: الموقع: - Lock قفل - Lock Guides قفل خطوط الإرشاد - Lock Slices قفل الشرائح - Long Lines خطوط طويلة - Long Strokes ضربات طويلة - Low منخفض - Luminosity السطوع - Magenta أرجواني - Magic Wand العصا السحرية - Magic Wand Tool أداة العصا السحرية - Make الشركة المصنعة - Make Clipping Mask إنشاء قناع قطع - Make Compound Path إنشاء مسار مركب - Make Guides إنشاء خطوط إرشاد - Mask قناع - Matte لون الحافة - Maximize تكبير - Maximum الحد الأقصى - Measure قياس - Medium متوسط - Medium Dots نقاط متوسطة - Medium Lines خطوط متوسطة - Medium Strokes ضربات متوسطة - Merge دمج - Merge Layers دمج الطبقات - Merged PRs طلبات السحب المدمجة - Mesh شبكة - Message: الرسالة: - Method الطريقة - Mezzotint… ميزوتينت… - Millimeters مليمترات - Minimize تصغير - Minimum الحد الأدنى - Minus Back طرح الخلفية - Minus Front طرح المقدمة - Mirror مرآة - Miter حادة - Mobile الجوال - Mode الوضع - Mode: الوضع: - Model الطراز - Models النماذج - Modern حديث - Modify تعديل - Monitor RGB RGB الشاشة - Monochromatic أحادي اللون - Monochrome أحادي اللون - Move تحريك - Move Down تحريك لأسفل - Move Panel تحريك اللوحة - Move Up تحريك لأعلى - Multiply مضاعفة - Name الاسم - Name (A–Z) الاسم (أ–ي) - Name: الاسم: - Navigator الملاح - New جديد - New Group مجموعة جديدة - New Group… مجموعة جديدة… - New Layer… طبقة جديدة… - New Set… مجموعة جديدة… - New Swatch… عينة لون جديدة… - New Workspace مساحة عمل جديدة - New Workspace… مساحة عمل جديدة… - New… جديد… - No contributor data was built into this copy. لم يتم تضمين بيانات المساهمين في هذه النسخة. - No Dither بلا ترقيش - No document لا يوجد مستند - No document open لا يوجد مستند مفتوح - No model credits were built into this copy. لم يتم تضمين بيانات الإشادة بالنماذج في هذه النسخة. - Noise تشويش - None بلا - Normal عادي - Note Paper ورق ملاحظات - NTSC Colors ألوان NTSC - Object كائن - Odd Fields حقول فردية - Off إيقاف - Offset إزاحة - OK موافق - Only Web Colors ألوان الويب فقط - Opacity العتامة - Opacity: العتامة: - Open فتح - Open Documents As Tabs فتح المستندات كعلامات تبويب - Open… فتح… - Optimized محسّن - Options الخيارات - Options… خيارات… - Orange برتقالي - Ordinals أرقام ترتيبية - Orientation الاتجاه - Original الأصلي - Other أخرى - Outer Glow… توهج خارجي… - Outline مخطط تفصيلي - Outline Stroke تحديد مسار الحد - Output الإخراج - Output: الإخراج: - Outside خارج - Overlay تراكب - Overlay Edge تراكب الحافة - Overprint طباعة فوقية - Overprint Preview معاينة الطباعة الفوقية - Package… تجميع الحزمة… - Paintbrush فرشاة الطلاء - Panel menu قائمة اللوحة - Panel Options… خيارات اللوحة… - Panels اللوحات - Paragraph فقرة - Paragraph Styles أنماط الفقرات - Paste لصق - Paste in Back لصق في الخلف - Paste in Front لصق في المقدمة - Paste in Place لصق في المكان - Paste on All Artboards لصق على كافة لوحات العمل - Path مسار - Path Eraser ممحاة المسار - Pathfinder مستكشف المسارات - Paths المسارات - Pattern النقشة - Pen القلم - Pen Tool أداة القلم - Pencil قلم رصاص - Pencil Tool أداة القلم الرصاص - Perceptual إدراكي - Performance الأداء - Perspective منظور - Perspective Grid شبكة المنظور - Photocopy نسخ ضوئي - Picas بيكا - Pixel بكسل - Pixel Preview معاينة البكسل - Pixelate بكسلة - Pixels بكسل - Place… إدراج… - Plaster جبس - Plug-ins المكونات الإضافية - Plug-ins & Scratch Disks المكونات الإضافية وأقراص العمل المؤقتة - Point Sample عينة نقطية - Pointillize… تنقيط… - Points نقاط - Polar Grid شبكة قطبية - Polygon مضلع - Polygon Tool أداة المضلع - Portrait عمودي - Position الموضع - Postcard بطاقة بريدية - Preferences التفضيلات - Preserve الاحتفاظ - PRESET DETAILS تفاصيل الإعداد المسبق - Preset Name اسم الإعداد المسبق - Preset: الإعداد المسبق: - Presets إعدادات مسبقة - Presets: الإعدادات المسبقة: - Press keys… اضغط المفاتيح… - Pressure الضغط - Preview معاينة - Print طباعة - Print Tiling تجانب الطباعة - Printer الطابعة - Print… طباعة… - Progressive تدريجي - Proof Colors ألوان المعاينة الطباعية - Proof Setup إعداد المعاينة الطباعية - Properties الخصائص - Public Domain ملكية عامة - Pucker انكماش - Punctuation علامات الترقيم - Puppet Warp التواء الدمية - Purple بنفسجي - Quality الجودة - Quick Actions إجراءات سريعة - Quickly start a new file بدء ملف جديد بسرعة - Radial شعاعي - Radial Blur… ضبابية شعاعية… - Radial Gradient تدرج شعاعي - Radius نصف القطر - Radius: نصف القطر: - Random عشوائي - Range: النطاق: - Rasterize تنقيط - Rasterize… تنقيط… - Ratio النسبة - Real name الاسم الحقيقي - Rearrange All Artboards… إعادة ترتيب كافة لوحات العمل… - Recent الأخيرة - Recent Files الملفات الأخيرة - Recolor Artwork… إعادة تلوين العمل الفني… - Rectangle مستطيل - Rectangle Tool أداة المستطيل - Rectangular Grid شبكة مستطيلة - Red أحمر - Redo إعادة - Reflect انعكاس - Regular عادي - Relative نسبي - Relative Colorimetric قياس لوني نسبي - Release Clipping Mask تحرير قناع القطع - Release Compound Path تحرير المسار المركب - Release Guides تحرير خطوط الإرشاد - Remove إزالة - Remove Anchor Points إزالة نقاط الإرساء - Rename إعادة تسمية - Rename Group… إعادة تسمية المجموعة… - Rename… إعادة تسمية… - Repeat تكرار - Replace استبدال - Reselect إعادة التحديد - Reset إعادة تعيين - Reset Preferences إعادة تعيين التفضيلات - Reset to Default إعادة تعيين إلى الافتراضي - Reshape إعادة تشكيل - Resize panel window تغيير حجم نافذة اللوحة - Resize panels تغيير حجم اللوحات - Resolution: الدقة: - Restore استعادة - Reticulation تشبيك - Reverse Path Direction عكس اتجاه المسار - Reverse the order عكس الترتيب - Revert استعادة - RGB Color ألوان RGB - Right يمين - Right-to-Left Paragraph Direction اتجاه الفقرة من اليمين إلى اليسار - Right: يمين: - Roman روماني - Rotate تدوير - Rotate View تدوير العرض - Rotate View Tool أداة تدوير العرض - Rotation تدوير - Round مستديرة - Rounded Rectangle مستطيل مستدير الزوايا - Roundness: الاستدارة: - Rulers المساطر - Rulers & Grids المساطر والشبكات - Saturate زيادة التشبع - Saturation التشبع - Save حفظ - Save a Copy… حفظ نسخة… - Save As… حفظ باسم… - Save for Web (Legacy)… حفظ للويب (قديم)… - Save Preset… حفظ الإعداد المسبق… - Save Selection حفظ التحديد - Save Selection… حفظ التحديد… - Saved تم الحفظ - Save… حفظ… - Scale تحجيم - Scale Cursor Proportional to UI تحجيم المؤشر بالتناسب مع واجهة المستخدم - Scale: المقياس: - Scallop تسنن - Scatter تبعثر - Scissors مقص - Scratch Disks أقراص التخزين المؤقت - Screen شاشة - Screen Mode وضع الشاشة - Scripts البرامج النصية - Search بحث - Select تحديد - Select All تحديد الكل - Select: التحديد: - Selection تحديد - Selection & Anchor Display التحديد وعرض نقاط الإرساء - Selective انتقائي - Send Backward إرسال للخلف - Send to Back إرسال إلى المؤخرة - Set: المجموعة: - Settings… إعدادات… - Shape شكل - Shape Builder منشئ الأشكال - Shape: الشكل: - Shapes الأشكال - Sharpen زيادة الحدة - Shear إمالة - Shear… قص مائل… - Shift Shift - Short Lines خطوط قصيرة - Short Strokes ضربات قصيرة - Show إظهار - Show All إظهار الكل - Show Bounding Box إظهار مربع الإحاطة - Show Grid إظهار الشبكة - Show Guides إظهار خطوط الإرشاد - Show in Folder إظهار في المجلد - Show Mesh إظهار الشبكة - Show Rulers إظهار المساطر - Show Tool Group Labels إظهار تسميات مجموعات الأدوات - Show Transparency Grid إظهار شبكة الشفافية - Show: إظهار: - Sides: الأضلاع: - Simplify… تبسيط… - Simulate Paper محاكاة الورق - Size الحجم - Size: الحجم: - Skew إمالة - Slice Options… خيارات الشريحة… - Slice Tool أداة الشريحة - Slices الشرائح - Small صغير - Small Caps أحرف استهلالية صغيرة - Smaller ↔ Larger أصغر ↔ أكبر - Smart Blur… ضبابية ذكية… - Smart Guides خطوط الإرشاد الذكية - Smooth تنعيم - Snap to Grid محاذاة إلى الشبكة - Soft ناعم - Soft Light ضوء خافت - Softness النعومة - Solid مصمت - Sort فرز - Spacing التباعد - Spin دوران - Spiral حلزون - Sponge إسفنجة - Spot Color لون موضعي - Square مربع - Stamp ختم - Standard قياسي - Standard Ligatures حروف مركبة قياسية - Star نجمة - Step Backward خطوة للخلف - Step Forward خطوة للأمام - Stop إيقاف - Strength القوة - Strikethrough يتوسطه خط - Stroke الحد - Patterns النقشات - Stroke Options خيارات الحدود - Stroke: حدود: - Style النمط - Stylize تنميط - Subdivisions التقسيمات الفرعية - Subtract طرح - Swash حروف مزخرفة - Swatches عينات الألوان - Symbol Sprayer بخاخ الرموز - Symbols الرموز - System Title Bar شريط عنوان النظام - Table جدول - Tabloid Tabloid - Taper التناقص التدريجي - Target الهدف - Target: الهدف: - Temperature درجة الحرارة - Texture الملمس - Thickness السماكة - Threshold العتبة - Tile تجانب - Tint صبغة - Tolerance التفاوت - Tolerance: التفاوت: - Tool أداة - Tools الأدوات - Top أعلى - Top Left أعلى اليسار - Top Right أعلى اليمين - Top: أعلى: - Torn Edges حواف ممزقة - Total: الإجمالي: - Tracking تباعد الأحرف - Transform تحويل - Transparency الشفافية - Transparent شفاف - Trap… حصر الألوان… - Triangle مثلث - Trim قص الحواف - Twirl دوامة - Twist لف - Type نوع - Type: النوع: - Type… النص… - UI Scaling تحجيم واجهة المستخدم - Underline تسطير - Undo تراجع - Ungroup فك التجميع - Uniform منتظم - Unite توحيد - Units الوحدات - Unknown غير معروف - Unlock All إلغاء قفل الكل - Unsharp Mask… قناع الحدة… - Untitled بدون عنوان - Use Default استخدام الافتراضي - User Interface واجهة المستخدم - Username اسم المستخدم - Variables المتغيرات - Version الإصدار - Vertical عمودي - Vertical Type Tool أداة النص العمودي - Very High عالٍ جدًا - Video فيديو - View عرض - Violet بنفسجي - Visibility الرؤية - W: العرض: - Warp التواء - Water Paper ورق مائي - Wave… موجة… - Weight الوزن - Weight: السمك: - White أبيض - Width العرض - Width: العرض: - Window نافذة - Windows Windows - Working CMYK مساحة عمل CMYK - Workspace مساحة العمل - Wrinkle تجعد - Yellow أصفر - Zoom تكبير/تصغير - Zoom In تكبير - Zoom Out تصغير - Zoom Tool أداة التكبير/التصغير - “{name}” already exists. Replace it? “{name}” موجود بالفعل. هل تريد استبداله؟ -@plural agrees with {n} default shortcut|agrees with {n} default shortcuts يتطابق مع {n} اختصار افتراضي|يتطابق مع {n} اختصار افتراضي|يتطابق مع {n} اختصارين افتراضيين|يتطابق مع {n} اختصارات افتراضية|يتطابق مع {n} اختصارًا افتراضيًا|يتطابق مع {n} اختصار افتراضي -@plural Color Table ({n} color)|Color Table ({n} colors) جدول الألوان ({n} لون)|جدول الألوان ({n} لون)|جدول الألوان ({n} لونين)|جدول الألوان ({n} ألوان)|جدول الألوان ({n} لونًا)|جدول الألوان ({n} لون) -@plural Delete this {n} graphic style?|Delete these {n} graphic styles? هل تريد حذف هذا النمط الرسومي ({n})؟|هل تريد حذف هذا النمط الرسومي ({n})؟|هل تريد حذف هذين النمطين الرسوميين ({n})؟|هل تريد حذف هذه الأنماط الرسومية ({n})؟|هل تريد حذف هذه الأنماط الرسومية ({n})؟|هل تريد حذف هذه الأنماط الرسومية ({n})؟ -@plural {n} area highlighted|{n} areas highlighted {n} منطقة مميزة|{n} منطقة مميزة|{n} منطقتان مميزتان|{n} مناطق مميزة|{n} منطقةً مميزة|{n} منطقة مميزة -@plural {n} color|{n} colors {n} لون|{n} لون|{n} لونين|{n} ألوان|{n} لونًا|{n} لون @plural {n} commit|{n} commits {n} إيداع|{n} إيداع|{n} إيداعين|{n} إيداعات|{n} إيداعًا|{n} إيداع -@plural {n} fill|{n} fills {n} تعبئة|{n} تعبئة|{n} تعبئتان|{n} تعبئات|{n} تعبئةً|{n} تعبئة -@plural {n} glyph|{n} glyphs {n} محرف|{n} محرف|{n} محرفين|{n} محارف|{n} محرفًا|{n} محرف -@plural {n} item|{n} items {n} عنصر|{n} عنصر|{n} عنصران|{n} عناصر|{n} عنصرًا|{n} عنصر -@plural {n} Layer|{n} Layers {n} طبقة|{n} طبقة|{n} طبقتان|{n} طبقات|{n} طبقةً|{n} طبقة -@plural {n} more export waiting|{n} more exports waiting {n} عملية تصدير أخرى في الانتظار|{n} عملية تصدير أخرى في الانتظار|{n} عمليتا تصدير أخريان في الانتظار|{n} عمليات تصدير أخرى في الانتظار|{n} عملية تصدير أخرى في الانتظار|{n} عملية تصدير أخرى في الانتظار -@plural {n} object highlighted|{n} objects highlighted {n} كائن مميز|{n} كائن مميز|{n} كائنان مميزان|{n} كائنات مميزة|{n} كائنًا مميزًا|{n} كائن مميز -@plural {n} Object|{n} Objects {n} كائن|{n} كائن|{n} كائنان|{n} كائنات|{n} كائنًا|{n} كائن -@plural {n} part of the file wasn't read|{n} parts of the file weren't read لم يتم قراءة {n} جزء من الملف|لم يتم قراءة {n} جزء من الملف|لم يتم قراءة {n} جزءين من الملف|لم يتم قراءة {n} أجزاء من الملف|لم يتم قراءة {n} جزءًا من الملف|لم يتم قراءة {n} جزء من الملف -@plural {n} PR|{n} PRs {n} طلب سحب|{n} طلب سحب|{n} طلبا سحب|{n} طلبات سحب|{n} طلب سحب|{n} طلب سحب -@plural {n} shortcut is assigned more than once|{n} shortcuts are assigned more than once {n} اختصار تم تعيينه أكثر من مرة|{n} اختصار تم تعيينه أكثر من مرة|{n} اختصاران تم تعيينهما أكثر من مرة|{n} اختصارات تم تعيينها أكثر من مرة|{n} اختصارًا تم تعيينه أكثر من مرة|{n} اختصار تم تعيينه أكثر من مرة -@plural {n} star|{n} stars {n} نجمة|{n} نجمة|{n} نجمتان|{n} نجوم|{n} نجمةً|{n} نجمة -@plural {n} step|{n} steps {n} خطوة|{n} خطوة|{n} خطوتان|{n} خطوات|{n} خطوةً|{n} خطوة -@plural {n} stroke|{n} strokes {n} حد|{n} حد|{n} حدان|{n} حدود|{n} حدًا|{n} حد -3d Bevel مشطوفة -3d Light فاتح -3d Solid مصمت -3d Space Space -@msg Opened {url} تم فتح {url} -axis Both كلاهما -axis Horizontal أفقي -axis Vertical عمودي -effect Horizontal أفقي -effect Points نقاط -effect Regular عادي -effect Soft ناعم -effect Vertical عمودي -gradient-kind Radial شعاعي -imageTrace Outline مخطط تفصيلي -lighting Light فاتح -swatch Aqua أزرق مائي -swatch Black أسود -swatch Blue أزرق -swatch Copper نحاسي -swatch Cyan سماوي -swatch Green أخضر -swatch Indigo نيلي -swatch Magenta أرجواني -swatch Orange برتقالي -swatch Purple بنفسجي -swatch Red أحمر -swatch Violet بنفسجي -swatch White أبيض -swatch Yellow أصفر -theme Appearance المظهر - Gap فجوة - Exposure التعريض - Exposure… التعريض… - Desaturate إزالة التشبع - Adjustment تعديل - Brightness/Contrast السطوع/التباين - Hue/Saturation درجة اللون/التشبع diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7cb278ade3..69daee29cd 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -7,9 +7,9 @@ fn lang(code: &str) -> Lang { Lang::from_code(code).unwrap_or_else(|| panic!("{code} registered")) } -/// The languages that are not English, the source language. +/// The languages that are not English, the source language, and have complete catalogs. fn translated() -> Vec<Lang> { - Lang::all().filter(|l| *l != Lang::EN).collect() + Lang::all().filter(|l| l.complete_menus()).collect() } /// (language, context, English source, the term the language's glossary gives it). One row per @@ -164,21 +164,11 @@ fn numbered_labels_translate_the_name_before_the_number() { fn arabic_resolves_locales_and_preferences() { let ar = Lang::from_code("ar").expect("ar registered"); assert_eq!(ar.name(), "العربية"); - assert!(ar.complete_menus()); + assert!(!ar.complete_menus()); assert_eq!(Lang::from_pref("ar"), ar); for tag in ["ar", "AR", "ar-SA", "ar_EG", "ar_EG.UTF-8", "ar-AE", "ar-MA"] { assert_eq!(i18n().match_tag(tag), Some(ar), "{tag}"); } - for (en, want) in [ - ("Artboards", "لوحات العمل"), - ("Swatches", "عينات الألوان"), - ("Stroke", "الحد"), - ("Direct Selection", "تحديد مباشر"), - ("Save As…", "حفظ باسم…"), - ("Undo", "تراجع"), - ] { - assert_eq!(tr(ar, en), want, "{en}"); - } } #[test] @@ -741,8 +731,8 @@ fn message_dump_lists_the_reported_messages() { } /// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English. -const KEEPS_MENU_NAMES: [&str; 21] = - ["cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca", "ar"]; +const KEEPS_MENU_NAMES: [&str; 20] = + ["cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca"]; /// Menu labels the menu-complete catalogs (Czech, German, Spanish, Italian, Japanese, Brazilian Portuguese) show as they are: the product name, a format name, the built-in workspace /// names and the perspective grid presets (names, shown untranslated wherever else they appear). diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 697f3ecf06..0e92bec3f1 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -35,7 +35,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | -| Arabic | `ar` | 873 catalog entries: menus, preferences, tools, dialogs, commands and 6-form CLDR plurals; native Arabic name العربية | menus, dialogs, preferences | Arabic: document text has bidi layout and paragraph direction; interface strings render in Modern Standard Arabic via system fallback fonts; full shell mirroring pending STD-I18N-001 | no (AI-drafted, clean-room) | partial | 15–20 | +| Arabic | `ar` | registered with 6-form CLDR plurals and native name العربية; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) under AGENTS.md rule 16 | menus, dialogs, preferences | Arabic: document text has bidi layout and paragraph direction; interface strings render in Modern Standard Arabic via system fallback fonts; full shell mirroring pending STD-I18N-001 | no (AI-drafted, clean-room) | partial | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 7,553 rows, 1,682 of them `@msg` and 49 `@msgplural` (counted 2026-11-15 on `main` at `df984b2a02`): in `COMPLETE_MESSAGES`, and the untranslated report lists 50 missing menu strings, 35 `tl!` literals, 11 undo labels and 1,929 messages for it, the same sets as for Danish; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | From 9838fc1f1cf4a83d710f2cea900cbdc46676294f Mon Sep 17 00:00:00 2001 From: tareq <tareq.halaby@gmail.com> Date: Wed, 25 Nov 2026 08:12:15 +0100 Subject: [PATCH 15/71] refactor(i18n): make Arabic PR preparatory and keep unavailable to users until catalog is consumed - Keep Arabic unavailable in offered_codes, Language picker, and preference resolution - Verify CLDR 6-form plural rule and catalog parsing on custom instance - Update parity docs and leave #7665 open for the catalog consumer PR --- crates/ui-egui/src/i18n.rs | 5 +++-- crates/ui-egui/src/i18n/tests.rs | 24 +++++++++++++----------- docs/localization-parity.md | 2 +- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bd6fb2f56c..70d087cfb2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -74,9 +74,10 @@ static EMBEDDED: &Embedded = &[ /// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font /// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a -/// bundled Gujarati face) is not offered, including when restoring a preference. +/// bundled Gujarati face) is not offered, including when restoring a preference. Arabic is kept +/// unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed. fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> { - EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "gu" || !web || gujarati_font).collect() + EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect() } /// The one catalog set of the process, built on first use. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 69daee29cd..ad0f07c5e9 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -161,22 +161,24 @@ fn numbered_labels_translate_the_name_before_the_number() { } #[test] -fn arabic_resolves_locales_and_preferences() { - let ar = Lang::from_code("ar").expect("ar registered"); - assert_eq!(ar.name(), "العربية"); - assert!(!ar.complete_menus()); - assert_eq!(Lang::from_pref("ar"), ar); - for tag in ["ar", "AR", "ar-SA", "ar_EG", "ar_EG.UTF-8", "ar-AE", "ar-MA"] { - assert_eq!(i18n().match_tag(tag), Some(ar), "{tag}"); - } +fn arabic_is_preparatory_and_unavailable_to_users() { + assert_eq!(Lang::from_code("ar"), None); + assert!(!Lang::for_picker().iter().any(|l| l.code() == "ar")); + assert_eq!(Lang::from_pref("ar"), Lang::from_pref("auto")); } #[test] -fn arabic_plural_rule_has_six_forms() { - let ar = Lang::from_code("ar").expect("ar registered"); +fn arabic_plural_rule_and_catalog_infrastructure() { + let (i18n, problems) = I18n::new(EMBEDDED, &["ar"]); + assert!(problems.is_empty(), "{problems:?}"); + let ar = i18n.from_code("ar").expect("ar offered in custom instance"); + assert_eq!(i18n.name(ar), "العربية"); + for tag in ["ar", "AR", "ar-SA", "ar_EG", "ar_EG.UTF-8", "ar-AE", "ar-MA"] { + assert_eq!(i18n.match_tag(tag), Some(ar), "{tag}"); + } for (n, want) in [(0, "0 إيداع"), (1, "1 إيداع"), (2, "2 إيداعين"), (3, "3 إيداعات"), (11, "11 إيداعًا"), (100, "100 إيداع")] { - assert_eq!(trn(ar, n, "{n} commit", "{n} commits"), want, "for n={n}"); + assert_eq!(i18n.trn_plain(ar, n, "{n} commit", "{n} commits"), want, "for n={n}"); } } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 0e92bec3f1..1a2e2047f0 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -35,7 +35,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | -| Arabic | `ar` | registered with 6-form CLDR plurals and native name العربية; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) under AGENTS.md rule 16 | menus, dialogs, preferences | Arabic: document text has bidi layout and paragraph direction; interface strings render in Modern Standard Arabic via system fallback fonts; full shell mirroring pending STD-I18N-001 | no (AI-drafted, clean-room) | partial | 15–20 | +| Arabic | `ar` | registered with 6-form CLDR plurals and native name العربية; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) under AGENTS.md rule 16; preparatory registration kept unavailable in picker until upstream catalog is consumed | menus, dialogs, preferences | Arabic: document text has bidi layout and paragraph direction; interface strings render in Modern Standard Arabic via system fallback fonts; full shell mirroring pending STD-I18N-001 | no (AI-drafted, clean-room) | preparatory | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 7,553 rows, 1,682 of them `@msg` and 49 `@msgplural` (counted 2026-11-15 on `main` at `df984b2a02`): in `COMPLETE_MESSAGES`, and the untranslated report lists 50 missing menu strings, 35 `tl!` literals, 11 undo labels and 1,929 messages for it, the same sets as for Danish; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | From 2dcedf34fde2458c2ff2e7be6e1378088ef7345d Mon Sep 17 00:00:00 2001 From: tareq <tareq.halaby@gmail.com> Date: Wed, 25 Nov 2026 08:48:08 +0100 Subject: [PATCH 16/71] =?UTF-8?q?docs(i18n):=20align=20localization-parity?= =?UTF-8?q?=20Arabic=20row=20with=20preparatory=20PR=20scope=20(AGENTS.md?= =?UTF-8?q?=20=C2=A715)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/localization-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 1a2e2047f0..60ad923f00 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (Arabic (`ar`): catalog added with Modern Standard Arabic menus, preferences, tools, dialogs, commands and 6-form CLDR plurals; native name العربية; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** patch (Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; UI not exposed pending upstream `storytold/craft-i18n` catalog; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests) Per-language status of VectorCraft's interface. How the catalogs work and how to add a language: [`development.md` › Localisation](development.md#localisation). Part of @@ -35,7 +35,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | -| Arabic | `ar` | registered with 6-form CLDR plurals and native name العربية; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) under AGENTS.md rule 16; preparatory registration kept unavailable in picker until upstream catalog is consumed | menus, dialogs, preferences | Arabic: document text has bidi layout and paragraph direction; interface strings render in Modern Standard Arabic via system fallback fonts; full shell mirroring pending STD-I18N-001 | no (AI-drafted, clean-room) | preparatory | 15–20 | +| Arabic | `ar` | preparatory registration (native name العربية) and 6-form CLDR plural probe only; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) and not yet consumed | none (UI not exposed pending shared catalog) | document text: existing bidirectional layout and paragraph direction; interface UI: not exposed pending shared catalog, with full shell mirroring pending STD-I18N-001 | — (preparatory) | preparatory (not exposed) | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 7,553 rows, 1,682 of them `@msg` and 49 `@msgplural` (counted 2026-11-15 on `main` at `df984b2a02`): in `COMPLETE_MESSAGES`, and the untranslated report lists 50 missing menu strings, 35 `tl!` literals, 11 undo labels and 1,929 messages for it, the same sets as for Danish; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | @@ -101,7 +101,7 @@ font for the web build. | Date | Change | Summary | |---|---|---| -| 2026-11-24 | minor | Arabic (`ar`): catalog added with Modern Standard Arabic menus, preferences, tools, dialogs, commands and 6-form CLDR plurals; registered as twenty-sixth non-English language; native name العربية | +| 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) | | 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback and a glyph-coverage filter; status and error messages not yet translated; native review pending | From 4f404feb3f604e7f93f0a570b58b8c367f017d65 Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:51:19 +0430 Subject: [PATCH 17/71] fix(svg): preserve document units in legacy save dialogs - Keep missing legacy Save and SaveCopy units as Document/None, without changing engine serialization. - Preserve explicit saved units and Export/Export for Screens pixel defaults. - Cover captured SVG output for legacy saves, explicit overrides and Export defaults. --- crates/ui-egui/src/dialogs/screen_formats.rs | 2 +- crates/ui-egui/src/dialogs/svg_options.rs | 75 ++++++++++++++++++-- docs/ui-parity.md | 2 +- 3 files changed, 70 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index f01bc521ee..5a9d1645b1 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -509,7 +509,7 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map<String, Value>, presets: &[ let mine = fields.get("settings").and_then(|all| all.get(id)).and_then(Value::as_object).cloned().unwrap_or_default(); let tiny = mine.get("profile").and_then(Value::as_str) == Some("tiny12"); let params = match id { - "svg" => svg_options::svg_params(true, tiny), + "svg" => svg_options::svg_params(svg_options::Mode::Export, true, tiny), "pdf" => Vec::new(), _ => png_options::raster_params(id, true, None), }; diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index a48941f5c9..e9fc5a9794 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -56,7 +56,8 @@ const IMAGES: [(&str, &str); 2] = [("embed", "Embed"), ("link", "Link")]; const OBJECT_IDS: [(&str, &str); 3] = [("layerNames", "Layer Names"), ("minimal", "Minimal"), ("unique", "Unique")]; const PROFILES: [(&str, &str); 2] = [("svg11", "SVG 1.1"), ("tiny12", "SVG Tiny 1.2")]; const ENCODINGS: [(&str, &str); 3] = [("utf8", "Unicode (UTF-8)"), ("utf16", "Unicode (UTF-16)"), ("latin1", "ISO 8859-1")]; -const UNITS: [(&str, &str); 5] = [("px", "Pixels"), ("pt", "Points"), ("mm", "Millimeters"), ("cm", "Centimeters"), ("in", "Inches")]; +const UNITS: [(&str, &str); 6] = + [("document", "Document"), ("px", "Pixels"), ("pt", "Points"), ("mm", "Millimeters"), ("cm", "Centimeters"), ("in", "Inches")]; /// Dialog fields that are not SVG options. const UI_KEYS: [&str; 5] = ["mode", "path", "showCode", "allArtboards", "range"]; @@ -73,9 +74,9 @@ pub(crate) struct SvgCodeKey { selected: Option<Vec<vectorcraft_doc::NodeId>>, } -/// The options a first SVG Options dialog starts from: the engine's defaults with Pixels, -/// Internal CSS and Responsive on (as the reference app's Export As starts). Hidden layers are -/// left to the command (Save keeps them, Export leaves them out). +/// The options a first SVG export starts from: the engine's defaults with Pixels, +/// Internal CSS and Responsive on. Saves choose Document unless a remembered unit overrides it. +/// Hidden layers are left to the command (Save keeps them, Export leaves them out). pub(super) fn first_use() -> Map<String, Value> { let opts = vectorcraft_svg::ExportOptions { units: Some(vectorcraft_svg::SizeUnit::Px), ..Default::default() }; let mut m = serde_json::to_value(opts).ok().and_then(|v| v.as_object().cloned()).unwrap_or_default(); @@ -111,6 +112,10 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, mode: Mode, path: Option<&str> fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } + if mode != Mode::Export && saved.as_ref().unwrap_or(&app.ui.svg_options).get("units").is_none() { + // A document's legacy SVG options must not inherit Pixels from the last export. + fields.insert("units".into(), json!("document")); + } fields.insert("allArtboards".into(), json!(true)); fields.insert("range".into(), json!("")); if let Some(p) = path { @@ -148,7 +153,7 @@ fn pairs(key: &str, label: &'static str, choices: &[(&str, &'static str)]) -> Pa /// responsive, `<tspan>`s and metadata. `screens` (Export for Screens' Format Settings) leaves out /// Images and Variable Data: a linked image is another file. `tiny`: SVG Tiny has presentation /// attributes alone and no web fonts. -pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec<Param> { +pub(crate) fn svg_params(mode: Mode, screens: bool, tiny: bool) -> Vec<Param> { let styling = pairs("styling", tl!("Styling:"), &STYLING); let fonts = ParamKind::radio(FONTS.iter().map(|(v, l)| ((*v).to_string(), tl!(*l).into())).collect(), Some("false".into())); let (lo, hi) = (*vectorcraft_svg::DECIMALS.start() as f64, *vectorcraft_svg::DECIMALS.end() as f64); @@ -164,7 +169,8 @@ pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec<Param> { rows.push(Param::number("decimals", tl!("Decimal:"), 3.0, 1.0, 0).bounds(Some(lo), Some(hi))); rows.push(pairs("encoding", tl!("Encoding:"), &ENCODINGS)); // Responsive omits width and height, so the unit has nothing to act on. - rows.push(pairs("units", tl!("Units:"), &UNITS).enabled_when("responsive", false)); + let units = if mode == Mode::Export { &UNITS[1..] } else { &UNITS[..] }; + rows.push(pairs("units", tl!("Units:"), units).enabled_when("responsive", false)); rows.push(check("minify", tl!("Minify"), false)); rows.push(check("responsive", tl!("Responsive"), true)); // Embedded fonts need SVG 1.1 and text that stays text. @@ -193,7 +199,7 @@ fn artboard_rows(count: usize) -> Vec<Param> { /// Every row of the dialog for `mode`. Export Selection writes the selection's crop, without /// artboards to choose. fn dialog_params(mode: Mode, selection: bool, count: usize, tiny: bool) -> Vec<Param> { - let mut rows = svg_params(false, tiny); + let mut rows = svg_params(mode, false, tiny); match mode { Mode::Export if !selection => rows.extend(artboard_rows(count)), Mode::Export => {} @@ -215,6 +221,9 @@ fn options(mode: Mode, f: &DialogFields) -> Value { let tiny = f.text("profile") == Some("tiny12"); let mut o = json_of(&dialog_params(mode, false, 1, tiny), f); o.retain(|k, _| !UI_KEYS.contains(&k.as_str()) && !k.starts_with("__")); + if o.get("units").and_then(Value::as_str) == Some("document") { + o.remove("units"); + } if mode == Mode::Export { o.remove("preserveEditing"); if f.bool("useArtboards").unwrap_or(false) { @@ -686,6 +695,58 @@ mod tests { assert!(!svg.contains("mm\"") && svg.contains("viewBox=\"0 0 120 80\""), "{svg}"); } + #[test] + fn legacy_svg_saves_keep_document_units() { + for mode in [Mode::Save, Mode::SaveCopy] { + for last in [json!({"responsive": false}), json!({"responsive": false, "units": "px"})] { + let (mut app, written) = app(); + let original = std::env::temp_dir().join("vc-original.svg").to_string_lossy().replace('\\', "/"); + let path = std::env::temp_dir().join("vc-saved.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.run("file.saveAs", json!({"path": original, "svg": {"responsive": false}})).unwrap(); + let before = vectorcraft_svg::import(&text(&written, 0)).unwrap(); + app.ui.svg_options = last; + start(&mut app, mode, &path, false); + confirm(&mut app); + let after = vectorcraft_svg::import(&text(&written, 1)).unwrap(); + assert_eq!(after.units, vectorcraft_doc::Unit::Millimeters, "{mode:?}: {}", text(&written, 1)); + let (a, b) = (before.artboards[0].rect, after.artboards[0].rect); + assert!((a.width() - b.width()).abs() < 1e-6 && (a.height() - b.height()).abs() < 1e-6, "{mode:?}: {a:?} -> {b:?}"); + let expected = if mode == Mode::SaveCopy { &original } else { &path }; + assert_eq!(app.session.active().unwrap().path.as_deref(), Some(expected.as_str())); + } + } + } + + #[test] + fn svg_saves_keep_explicit_units_and_allow_pixel_overrides() { + for mode in [Mode::Save, Mode::SaveCopy] { + let (mut app, written) = app(); + let path = std::env::temp_dir().join("vc-explicit.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.run("file.saveAs", json!({"path": path, "svg": {"responsive": false, "units": "in"}})).unwrap(); + app.ui.svg_options = json!({"responsive": false, "units": "px"}); + start(&mut app, mode, &path, false); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 1)).unwrap().units, vectorcraft_doc::Unit::Inches); + start(&mut app, mode, &path, false); + set(&mut app, "units", json!("px")); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 2)).unwrap().units, vectorcraft_doc::Unit::Pixels); + } + } + + #[test] + fn svg_export_keeps_pixels_when_legacy_options_omit_units() { + let (mut app, written) = app(); + let path = std::env::temp_dir().join("vc-export.svg").to_string_lossy().replace('\\', "/"); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + app.ui.svg_options = json!({"responsive": false}); + start(&mut app, Mode::Export, &path, false); + confirm(&mut app); + assert_eq!(vectorcraft_svg::import(&text(&written, 0)).unwrap().units, vectorcraft_doc::Unit::Pixels); + } + /// OK with a range the document lacks keeps the dialog open with the reason, writes nothing and /// remembers nothing. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0b6caef602..df3ebfe937 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; 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) > -> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. +> SVG Options can write physical dimensions with Responsive off and a physical unit selected (#4462); pixel output remains bare numbers. Save As and Save a Copy offer Document units and preserve an existing SVG's physical units when legacy saved options omit a unit; Export keeps its Pixels default. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > From 60d16a5561581933565a5735c11dd7afbadb52c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 28 Nov 2026 22:20:43 -0800 Subject: [PATCH 18/71] Quick Pen: the arc-size wheel reads the framework's gesture, held keys and modal mark The Ctrl-wheel arc size now reads everything from the canvas's share of the craft wheel: its lines, its gesture's motion, the keys held during the gesture (held) and whether a modal layer held the turn (modal). The tool keeps no wheel timers or raw-event reads of its own. A turn the app's own modal window was up for stays muted until the framework starts a new gesture. Zoom-modifier motion adds both axes, as the zoom factor does. Pins craft-libs to the head of storytold/craft-libs#4220, which adds Wheel::held and Wheel::modal. --- Cargo.lock | 170 +++++++-------- Cargo.toml | 70 +++---- apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 209 +++++++------------ 5 files changed, 194 insertions(+), 259 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 520647b95d..74557685f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1239,7 +1239,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1280,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "crc32fast", "flate2", @@ -1291,7 +1291,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1302,7 +1302,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1310,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1335,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1353,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1371,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "egui", ] @@ -1388,7 +1388,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "md-5", "rayon", @@ -1397,12 +1397,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,7 +1422,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "rayon", ] @@ -1451,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1477,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1493,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "serde", ] @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1520,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1532,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "serde", "serde_json", @@ -1542,12 +1542,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1562,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1581,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1613,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "gif", ] @@ -1626,7 +1626,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "flate2", ] @@ -1634,7 +1634,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "chrono", "fixed_decimal", @@ -1675,7 +1675,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1720,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1728,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1739,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1754,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1768,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1786,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1798,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "encoding_rs", "image", @@ -1809,7 +1809,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "chrono", "craft-codepage", @@ -1819,7 +1819,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-keymap", @@ -1835,7 +1835,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "flate2", "serde", @@ -1846,7 +1846,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1858,7 +1858,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "async-channel", "async-io", @@ -1889,7 +1889,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1898,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-host", @@ -1922,7 +1922,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-eps", "flate2", @@ -1947,7 +1947,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "encoding_rs", "flate2", @@ -1958,7 +1958,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "dispatch2", "egui", @@ -1971,7 +1971,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1990,7 +1990,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-atomic", "craft-host", @@ -2007,7 +2007,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "fax", "hayro-ccitt", @@ -2018,7 +2018,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2039,7 +2039,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-keymap", @@ -2051,7 +2051,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2091,7 +2091,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-atomic", "craft-behavior", @@ -2106,7 +2106,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "serde", "thiserror 2.0.21", @@ -2116,7 +2116,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "serde", "thiserror 2.0.21", @@ -2125,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-keymap", @@ -2140,12 +2140,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2159,7 +2159,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-i18n", @@ -2175,7 +2175,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "accesskit", "craft-behavior", @@ -2213,7 +2213,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2224,7 +2224,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-host", @@ -2242,7 +2242,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-host", @@ -2263,7 +2263,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-host", @@ -2284,7 +2284,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-behavior", "craft-host", @@ -2303,7 +2303,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "base64 0.22.1", "chrono", @@ -2335,7 +2335,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "flate2", "serde", @@ -2346,7 +2346,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2356,7 +2356,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "js-sys", "serde_json", @@ -2367,7 +2367,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "winsafe", ] @@ -2375,7 +2375,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "craft-appkit", "craft-atomic", @@ -2407,7 +2407,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3762,7 +3762,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "brotli", "hayro-postscript", @@ -3771,7 +3771,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3789,7 +3789,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3807,12 +3807,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "flate2", "hayro-ccitt", @@ -4795,7 +4795,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4952,7 +4952,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=610c86792a02aa3d416926ee44e3ec3788dea853#610c86792a02aa3d416926ee44e3ec3788dea853" +source = "git+https://github.com/storytold/craft-libs?rev=bb7cc548d286085f2d288445123ec3679248da86#bb7cc548d286085f2d288445123ec3679248da86" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index a0fb986dcc..07d9278067 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,46 +11,46 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -193,13 +193,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index e8b56c29a9..687140ce2b 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -27,7 +27,7 @@ log = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bb7cc548d286085f2d288445123ec3679248da86", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fe2cbb7504..965c06f3b1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -328,7 +328,7 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O let task_bar = (app.ui.task_bar && !revolve_editing(app) && !strip && !dragging).then(|| task_bar::task_bar(app, ui, space)).flatten(); let bar = quick_pen_bar::quick_pen_bar(app, ui, space); // A Ctrl-wheel turn with the Quick Pen tool changes its arc size; the view stays as it was before the pass. - out.arc_turn = quick_pen_wheel::arc_size(app, ui, space.wheel(), bar); + out.arc_turn = quick_pen_wheel::arc_size(app, space.wheel(), bar); contour_bar::contour_bar(app, ui, space); // After the task bar, which the row of character alternates keeps clear of. alternates_bar::alternates_bar(app, ui, space, task_bar); diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs index 6a5b43de78..06ee24dd50 100644 --- a/crates/ui-egui/src/canvas/quick_pen_wheel.rs +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -4,53 +4,27 @@ //! and on macOS alike //! ([Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)). //! VectorCraft's own rules: a mouse wheel turned with Ctrl does the same; a mouse wheel makes one -//! step of 15°, as `[` and `]` do, for each notch (each whole wheel line, at least one for each pass +//! step of 15°, as `[` and `]` do, for each notch (each whole wheel line, at least one for each share //! of wheel motion the canvas reads), and a touchpad makes one step for each wheel line of its -//! motion; up makes the arc larger and down smaller, and sideways motion makes no step (with Ctrl on -//! Windows and Linux, where the wheel reaches the canvas as a zoom, sideways motion counts as up and -//! down); momentum after the fingers lift makes no step; and a turn ends after [`GESTURE_GAP`] -//! without a wheel event, as the framework's wheel gestures do, or after 1 s without one while a -//! touchpad gesture is under way. +//! gesture's motion; up makes the arc larger and down smaller, and sideways motion makes no step +//! (with Ctrl on Windows and Linux, where the wheel reaches the canvas as a zoom, sideways motion +//! counts as up and down); and momentum after the fingers lift makes no step. +//! +//! Everything here is read from the canvas's share of the framework's wheel (`space.wheel()`): its +//! modifiers, its device, its motion in lines (`lines`, or `zoom_lines` for a wheel that reaches the +//! canvas as a zoom), its gesture's motion so far (`gathered`, `zoom_gathered`), the keys held during +//! the gesture (`held`) and whether the gesture began under a modal window (`modal`). -use craft::behavior::{GESTURE_GAP, Wheel, WheelSource, WheelUnit}; +use craft::behavior::{Wheel, WheelSource, WheelUnit}; use craft::keymap::{Mods, Platform}; -use super::{Ui, VectorcraftApp, json}; - -/// A wheel turn the Quick Pen tool may take: the touchpad's motion, in wheel lines, not yet turned -/// into a step; whether the tool took the turn; whether the turn began under a modal window; -/// whether a touchpad gesture is under way (between its Start and End phases); when the turn's last -/// wheel event came (egui's input time); and the modifiers the gesture holds. -#[derive(Clone, Copy, Default, PartialEq)] -struct ArcWheel { - rest: f32, - taken: bool, - muted: bool, - gesture: bool, - last: f64, - held: Mods, -} - -/// What a pass's own wheel events say: whether any came, the modifiers of a touchpad gesture's -/// Start among them, and whether the gesture ended after it. -#[derive(Default)] -struct RawWheel { - any: bool, - start: Option<Mods>, - end: bool, -} - -/// Seconds without a wheel event after which a wheel event starts a new turn while a touchpad -/// gesture is under way (fingers resting mid-gesture); outside a gesture it is [`GESTURE_GAP`]. -const RESTING_GAP: f64 = 1.0; +use super::{VectorcraftApp, json}; /// Most steps one share of the wheel makes: from 1° to 359° is fewer than 24 steps of 15°. const MOST_STEPS: f32 = 24.0; -/// The modifiers held in `a` or in `b`. -fn either(a: Mods, b: Mods) -> Mods { - Mods { cmd: a.cmd || b.cmd, ctrl: a.ctrl || b.ctrl, alt: a.alt || b.alt, shift: a.shift || b.shift } -} +/// How far a line's worth of motion may fall short of a whole line and still count as one. +const LINE_SLACK: f32 = 1e-3; /// The Control key alone: Ctrl on Windows and Linux, which the keymap folds into `cmd`, and the /// Control key on macOS, where `cmd` is ⌘. @@ -59,27 +33,29 @@ fn ctrl_alone(m: Mods, os: Platform) -> bool { control && !(m.alt || m.shift) } -/// How far a line's worth of motion may fall short of a whole line and still count as one: a zoom -/// factor turned back into lines carries rounding. -const LINE_SLACK: f32 = 1e-3; - -/// The wheel's up and down motion in wheel lines, up positive. A wheel turned with egui's zoom -/// modifier (Ctrl on Windows and Linux) reaches the canvas as a zoom factor and no scroll, and so -/// does a touchpad's Ctrl+scroll there, which the framework reads as a pinch; the motion is read -/// back from the factor in lines of egui's `line_scroll_speed` points, at `scroll_zoom_speed` per -/// point, as egui and the framework made it. Points of a touchpad or a browser are lines of `line` -/// points. A wheel turned with the zoom modifier sideways counts as up and down: the factor does -/// not tell the two apart. -fn lines(wheel: &Wheel, ctx: &egui::Context, line: f32) -> f32 { - let lines = if wheel.scroll.y != 0.0 { +/// The share's up and down motion in wheel lines, up positive. A wheel turned with egui's zoom +/// modifier (Ctrl on Windows and Linux) reaches the canvas as a zoom, and the framework counts its +/// lines in `zoom_lines`; sideways motion there adds to up and down, as egui's zoom factor does. +/// Points of a touchpad or a browser are lines of `line` points. +fn lines(wheel: &Wheel, line: f32) -> f32 { + let d = if wheel.zoom_lines != egui::Vec2::ZERO { + wheel.zoom_lines.x + wheel.zoom_lines.y + } else if wheel.scroll.y != 0.0 { if wheel.unit == WheelUnit::Line { wheel.lines.y } else { wheel.scroll.y / line } - } else if wheel.scroll == egui::Vec2::ZERO && wheel.zoom.is_finite() && wheel.zoom > 0.0 && wheel.zoom != 1.0 { - let (speed, egui_line) = ctx.options(|o| (o.input_options.scroll_zoom_speed, o.input_options.line_scroll_speed)); - wheel.zoom.ln() / speed / egui_line } else { 0.0 }; - if lines.is_finite() { lines } else { 0.0 } + if d.is_finite() { d } else { 0.0 } +} + +/// A wheel turn the Quick Pen tool reads, from the framework's gesture: whether a modal window was up +/// during it, whether the tool took it, and the touchpad motion it took, in wheel lines, not yet +/// turned into a step. +#[derive(Clone, Copy, Default, PartialEq)] +struct ArcTurn { + muted: bool, + taken: bool, + rest: f32, } /// Whether `wheel`, of `lines` wheel lines, comes from a touchpad and not from a mouse wheel's @@ -96,99 +72,61 @@ fn fine(wheel: &Wheel, lines: f32) -> bool { } } +/// Whole lines in `v`, toward zero, with [`LINE_SLACK`] for rounding. +fn whole(v: f32) -> f32 { + (v + LINE_SLACK * v.signum()).trunc() +} + /// The steps `wheel` makes, up positive: a mouse wheel's whole lines, at least one; one for a share -/// of points or pages from a mouse; and a touchpad's motion in wheel lines of `line` points, with -/// the fraction kept in `rest` for later motion. Momentum after the fingers lift makes no step. -fn steps(wheel: &Wheel, ctx: &egui::Context, line: f32, rest: &mut f32) -> f32 { +/// of points or pages from a mouse; and for a touchpad the whole lines of the motion the tool took in +/// this turn, with the fraction kept in `rest`. Momentum after the fingers lift makes no step. +fn steps(wheel: &Wheel, line: f32, rest: &mut f32) -> f32 { if wheel.source == WheelSource::Momentum { return 0.0; } - let d = lines(wheel, ctx, line); + let d = lines(wheel, line); if d == 0.0 { return 0.0; } if fine(wheel, d) { *rest += d; - let whole = (*rest + LINE_SLACK * rest.signum()).trunc(); - *rest -= whole; - return whole.clamp(-MOST_STEPS, MOST_STEPS); + let steps = whole(*rest); + *rest -= steps; + return steps.clamp(-MOST_STEPS, MOST_STEPS); } - let whole = if wheel.unit == WheelUnit::Line { (d.abs() + LINE_SLACK).trunc() } else { 1.0 }; - d.signum() * whole.clamp(1.0, MOST_STEPS) + let notches = if wheel.unit == WheelUnit::Line { (d.abs() + LINE_SLACK).trunc() } else { 1.0 }; + d.signum() * notches.clamp(1.0, MOST_STEPS) } /// With the Quick Pen tool active, the wheel share the canvas read this pass (`wheel`), turned with /// the Control key alone and not over the Quick Pen toolbar (`bar`), makes the arc size larger (up) -/// or smaller (down). The modifiers held at any point of a touchpad gesture count until it ends, -/// keys tapped between its wheel events included. No step is made while a modal window is up, nor -/// for the rest of a turn begun under one. Returns true while the tool takes the turn, so the view -/// does not zoom or scroll for the rest of it. -pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, wheel: Option<Wheel>, bar: Option<egui::Rect>) -> bool { - let id = egui::Id::unique("quick-pen-arc-wheel"); - let before: ArcWheel = ui.data(|d| d.get_temp(id)).unwrap_or_default(); - let os = crate::keymap::platform(); - let mut now = before; - // The pass's own events: the keys, and the wheel's events with the phases of a touchpad gesture, - // which the canvas's share does not carry when they move nothing (a gesture's Start). - let (time, raw, keys) = ui.input(|i| { - let mut keys = Mods::NONE; - let mut raw = RawWheel::default(); - for e in &i.events { - match e { - egui::Event::ModifiersChanged(m) | egui::Event::Key { modifiers: m, .. } => keys = either(keys, Mods::from_egui(m, os)), - // The framework's pinch from a Ctrl+wheel on Windows and Linux. - egui::Event::Zoom(_) => raw.any = true, - egui::Event::MouseWheel { phase, modifiers, .. } => { - raw.any = true; - match phase { - egui::TouchPhase::Start => { - raw.start = Some(either(raw.start.unwrap_or(Mods::NONE), Mods::from_egui(modifiers, os))); - raw.end = false; - } - egui::TouchPhase::End | egui::TouchPhase::Cancel => raw.end = true, - egui::TouchPhase::Move => {} - } - } - _ => {} - } - } - (i.time, raw, keys) - }); - let gap = if now.gesture { RESTING_GAP } else { GESTURE_GAP }; - if raw.any && (time - now.last > gap || raw.start.is_some()) { - // A wheel event after the gap, or a touchpad gesture's start, begins a new turn: what the - // turn before it took and left over goes. - now = ArcWheel::default(); - } - if let Some(m) = raw.start { - now.gesture = true; - now.held = m; - } - if now.gesture { - now.held = either(now.held, keys); - } - if raw.any { - now.last = time; - } - // The canvas reads no wheel under a modal window: a turn that goes on there makes no step after - // the window closes either. - let modal = crate::panel_docking::modal_window_up(app); - if modal && raw.any { - now.muted = true; - } - let mut runs = 0.0; +/// or smaller (down). A touchpad gesture counts the keys held at any point of it, keys tapped +/// between its events included. No step is made while a modal window is up, nor for the rest of a +/// turn begun under one. Returns true while the tool takes the turn, so the view does not zoom or +/// scroll for the rest of it. A turn is the framework's wheel gesture. +pub(super) fn arc_size(app: &mut VectorcraftApp, wheel: Option<Wheel>, bar: Option<egui::Rect>) -> bool { + let Some(w) = wheel else { return false }; + let id = egui::Id::unique("quick-pen-arc-turn"); + // The framework's first share of a gesture gathers only itself. + let first = w.gathered == w.scroll && w.zoom_gathered == w.zoom_lines; + let before = if first { ArcTurn::default() } else { app.ui_ctx.as_ref().and_then(|ctx| ctx.data(|d| d.get_temp(id))).unwrap_or_default() }; + let mut turn = before; + // The framework marks a turn a modal layer held (`modal`); a turn that reached the canvas while + // one of the app's own modal windows was up stays muted until the framework starts a new one. + turn.muted |= w.modal || crate::panel_docking::modal_window_up(app); + let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); + let mods = if fine(&w, lines(&w, line)) { w.held } else { w.mods }; + let over_bar = w.at.zip(bar).is_some_and(|(at, bar)| bar.contains(at)); let quick_pen = app.session.tool_id() == vectorcraft_tools::quickpen::ID; - if let Some(w) = wheel.filter(|_| !modal) { - now.held = if now.gesture { either(now.held, w.mods) } else { w.mods }; - let over_bar = w.at.zip(bar).is_some_and(|(at, bar)| bar.contains(at)); - if quick_pen && !now.muted && !over_bar && ctrl_alone(now.held, os) { - now.taken = true; - let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); - runs = steps(&w, ui.ctx(), line, &mut now.rest); - } + let mut runs = 0.0; + if quick_pen && !turn.muted && !over_bar && ctrl_alone(mods, crate::keymap::platform()) { + turn.taken = true; + runs = steps(&w, line, &mut turn.rest); } - if raw.end { - now.gesture = false; + if (first || turn != before) + && let Some(ctx) = &app.ui_ctx + { + ctx.data_mut(|d| d.insert_temp(id, turn)); } let cmd = if runs > 0.0 { "tool.quickPen.arcLarger" } else { "tool.quickPen.arcSmaller" }; for _ in 0..(runs.abs() as u32) { @@ -201,8 +139,5 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ui: &Ui, wheel: Option<Wheel>, } } } - if now != before { - ui.data_mut(|d| d.insert_temp(id, now)); - } - quick_pen && wheel.is_some() && now.taken + quick_pen && turn.taken } From 411abb2f86621db04d3c242ab53eee39bb70adc6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 29 Nov 2026 21:54:37 -0800 Subject: [PATCH 19/71] Quick Pen: Ctrl+wheel arc size reads the framework's wheel claims The arc size keeps no per-gesture state of its own: each share the tool reads is claimed with CanvasSpace::claim_wheel, the touchpad motion not yet turned into a step rides in claimed_spent, and an app modal window marks the gesture with mark_wheel_modal. craft-libs moves to main at 5190e08ab, which has the wheel claim API (craft-libs #4373). --- Cargo.lock | 207 +++++++++---------- Cargo.toml | 74 +++---- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 55 +++-- 4 files changed, 165 insertions(+), 173 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4fce3ecad1..4f79f80d81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,12 +626,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -725,6 +719,17 @@ dependencies = [ "brotli-decompressor 5.0.3", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -1184,19 +1189,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1239,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "crc32fast", "flate2", @@ -1291,18 +1283,19 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "egui", ] @@ -1388,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "md-5", "rayon", @@ -1397,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1433,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1443,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "rayon", ] @@ -1451,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", ] @@ -1501,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "serde_json", @@ -1542,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "gif", ] @@ -1626,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", ] @@ -1634,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,8 +1640,10 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", "chrono", "fixed_decimal", "icu_calendar", @@ -1675,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "encoding_rs", "image", @@ -1809,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "chrono", "craft-codepage", @@ -1827,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1843,7 +1838,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "serde", @@ -1854,7 +1849,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1866,12 +1861,12 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "async-channel", "async-io", "async-process", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", @@ -1881,6 +1876,8 @@ dependencies = [ "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "rfd", "serde", "serde_json", @@ -1897,7 +1894,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1906,7 +1903,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -1930,7 +1927,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1941,7 +1938,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-eps", "flate2", @@ -1955,7 +1952,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "encoding_rs", "flate2", @@ -1966,7 +1963,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "dispatch2", "egui", @@ -1979,7 +1976,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1998,7 +1995,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-atomic", "craft-host", @@ -2015,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fax", "hayro-ccitt", @@ -2026,7 +2023,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2047,7 +2044,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2059,7 +2056,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2084,7 +2081,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2099,7 +2096,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2114,7 +2111,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2124,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2133,7 +2130,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2148,12 +2145,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2167,7 +2164,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-i18n", @@ -2183,7 +2180,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "accesskit", "craft-behavior", @@ -2221,7 +2218,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2232,7 +2229,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2250,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2271,7 +2268,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2292,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2311,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.22.1", "chrono", @@ -2343,7 +2340,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "serde", @@ -2354,7 +2351,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2375,7 +2372,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "winsafe", ] @@ -2383,7 +2380,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2415,7 +2412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3770,16 +3767,16 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3797,7 +3794,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3815,12 +3812,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "hayro-ccitt", @@ -4803,7 +4800,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4960,7 +4957,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index cc76d129c5..a3e05e0732 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,49 +10,49 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Nightly profile isolation, launch protocol, and security fence. craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # internal @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 84bb417676..34b6d7e5df 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -329,7 +329,7 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O let task_bar = (app.ui.task_bar && !revolve_editing(app) && !strip && !dragging).then(|| task_bar::task_bar(app, ui, space)).flatten(); let bar = quick_pen_bar::quick_pen_bar(app, ui, space); // A Ctrl-wheel turn with the Quick Pen tool changes its arc size; the view stays as it was before the pass. - out.arc_turn = quick_pen_wheel::arc_size(app, space.wheel(), bar); + out.arc_turn = quick_pen_wheel::arc_size(app, ui.ctx(), space, bar); contour_bar::contour_bar(app, ui, space); // After the task bar, which the row of character alternates keeps clear of. alternates_bar::alternates_bar(app, ui, space, task_bar); diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs index 06ee24dd50..b66ad3963e 100644 --- a/crates/ui-egui/src/canvas/quick_pen_wheel.rs +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -17,6 +17,7 @@ use craft::behavior::{Wheel, WheelSource, WheelUnit}; use craft::keymap::{Mods, Platform}; +use craft::ui::canvas::CanvasSpace; use super::{VectorcraftApp, json}; @@ -48,16 +49,6 @@ fn lines(wheel: &Wheel, line: f32) -> f32 { if d.is_finite() { d } else { 0.0 } } -/// A wheel turn the Quick Pen tool reads, from the framework's gesture: whether a modal window was up -/// during it, whether the tool took it, and the touchpad motion it took, in wheel lines, not yet -/// turned into a step. -#[derive(Clone, Copy, Default, PartialEq)] -struct ArcTurn { - muted: bool, - taken: bool, - rest: f32, -} - /// Whether `wheel`, of `lines` wheel lines, comes from a touchpad and not from a mouse wheel's /// notches. egui names the source on macOS and reports it unknown elsewhere. There, point motion /// (Wayland, a Windows precision touchpad) and line motion that is not whole lines (Windows and X11) @@ -103,30 +94,34 @@ fn steps(wheel: &Wheel, line: f32, rest: &mut f32) -> f32 { /// or smaller (down). A touchpad gesture counts the keys held at any point of it, keys tapped /// between its events included. No step is made while a modal window is up, nor for the rest of a /// turn begun under one. Returns true while the tool takes the turn, so the view does not zoom or -/// scroll for the rest of it. A turn is the framework's wheel gesture. -pub(super) fn arc_size(app: &mut VectorcraftApp, wheel: Option<Wheel>, bar: Option<egui::Rect>) -> bool { - let Some(w) = wheel else { return false }; - let id = egui::Id::unique("quick-pen-arc-turn"); - // The framework's first share of a gesture gathers only itself. - let first = w.gathered == w.scroll && w.zoom_gathered == w.zoom_lines; - let before = if first { ArcTurn::default() } else { app.ui_ctx.as_ref().and_then(|ctx| ctx.data(|d| d.get_temp(id))).unwrap_or_default() }; - let mut turn = before; - // The framework marks a turn a modal layer held (`modal`); a turn that reached the canvas while - // one of the app's own modal windows was up stays muted until the framework starts a new one. - turn.muted |= w.modal || crate::panel_docking::modal_window_up(app); +/// scroll for the rest of it. A turn is the framework's wheel gesture, and the tool keeps no state of +/// its own: it claims each share it reads (`CanvasSpace::claim_wheel`), recording as `spent.x` the +/// touchpad motion it kept, in wheel lines, so `claimed_spent.x` is the motion of the turn not yet +/// turned into a step. +pub(super) fn arc_size(app: &mut VectorcraftApp, ctx: &egui::Context, space: &CanvasSpace, bar: Option<egui::Rect>) -> bool { + let Some(w) = space.wheel() else { return false }; + // The framework marks a turn a modal layer held (`modal`); a turn that reaches the canvas while one + // of the app's own modal windows is up is marked too, and stays muted until the framework starts a + // new one. + let app_modal = crate::panel_docking::modal_window_up(app); + if app_modal { + space.mark_wheel_modal(ctx); + } + let muted = w.modal || app_modal; let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); let mods = if fine(&w, lines(&w, line)) { w.held } else { w.mods }; let over_bar = w.at.zip(bar).is_some_and(|(at, bar)| bar.contains(at)); let quick_pen = app.session.tool_id() == vectorcraft_tools::quickpen::ID; + let mut taken = w.claimed; let mut runs = 0.0; - if quick_pen && !turn.muted && !over_bar && ctrl_alone(mods, crate::keymap::platform()) { - turn.taken = true; - runs = steps(&w, line, &mut turn.rest); - } - if (first || turn != before) - && let Some(ctx) = &app.ui_ctx - { - ctx.data_mut(|d| d.insert_temp(id, turn)); + if quick_pen && !muted && !over_bar && ctrl_alone(mods, crate::keymap::platform()) { + let mut rest = w.claimed_spent.x; + let made = steps(&w, line, &mut rest); + // A share of a gesture another scroller owns cannot be claimed; the tool still takes it, as the + // canvas's output keeps the view for this pass. + space.claim_wheel(ctx, egui::vec2(rest - w.claimed_spent.x, 0.0)); + taken = true; + runs = made; } let cmd = if runs > 0.0 { "tool.quickPen.arcLarger" } else { "tool.quickPen.arcSmaller" }; for _ in 0..(runs.abs() as u32) { @@ -139,5 +134,5 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, wheel: Option<Wheel>, bar: Opti } } } - quick_pen && turn.taken + quick_pen && taken } From f4888892d02d7e7202f7ce162c3c7014957d8163 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 29 Nov 2026 22:36:16 -0800 Subject: [PATCH 20/71] Quick Pen: the first Ctrl+wheel share keeps the view; English-only labels The arc-size wheel is now read before the canvas body, so on the first share of a turn the controls, painting and tool host use the view the pass began with instead of the zoomed one. The framework reports a frame's wheel motion as signed totals, so opposite notches in one frame cancel; the docs say so. The arc size labels are English only, as new strings go through craft-i18n. --- crates/ui-egui/src/canvas.rs | 43 ++++++++++++++++--- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 14 ++++-- crates/ui-egui/src/i18n/bg.tsv | 2 - crates/ui-egui/src/i18n/bs.tsv | 2 - crates/ui-egui/src/i18n/ca.tsv | 2 - crates/ui-egui/src/i18n/cs.tsv | 2 - crates/ui-egui/src/i18n/da.tsv | 2 - crates/ui-egui/src/i18n/de.tsv | 2 - crates/ui-egui/src/i18n/el.tsv | 2 - crates/ui-egui/src/i18n/es.tsv | 2 - crates/ui-egui/src/i18n/fi.tsv | 2 - crates/ui-egui/src/i18n/fr.tsv | 2 - crates/ui-egui/src/i18n/gu.tsv | 2 - crates/ui-egui/src/i18n/hi.tsv | 2 - crates/ui-egui/src/i18n/hu.tsv | 2 - crates/ui-egui/src/i18n/id.tsv | 2 - crates/ui-egui/src/i18n/it.tsv | 2 - crates/ui-egui/src/i18n/ja.tsv | 2 - crates/ui-egui/src/i18n/ka.tsv | 2 - crates/ui-egui/src/i18n/ko.tsv | 2 - crates/ui-egui/src/i18n/nl.tsv | 2 - crates/ui-egui/src/i18n/pl.tsv | 2 - crates/ui-egui/src/i18n/pt-br.tsv | 2 - crates/ui-egui/src/i18n/ru.tsv | 2 - crates/ui-egui/src/i18n/sv.tsv | 2 - crates/ui-egui/src/i18n/tr.tsv | 2 - crates/ui-egui/src/i18n/uk.tsv | 2 - crates/ui-egui/src/i18n/vi.tsv | 2 - crates/ui-egui/src/i18n/zh-hans.tsv | 2 - crates/ui-egui/src/i18n/zh-hant.tsv | 2 - crates/ui-egui/src/tests/quickpenwheel.rs | 45 ++++++++++++++++++++ docs/mcp.md | 11 +++-- 32 files changed, 99 insertions(+), 70 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 34b6d7e5df..f6ac38176b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -6,7 +6,7 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, - canvas_space, tool_pass, + canvas_space, tool_pass, with_canvas_space, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::primitives::PaintSlot; @@ -232,8 +232,31 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin }; let mut body = Body::default(); let shown = canvas.show(ui, |ui, env| { - if let Some(space) = canvas_space(&env.env) { - body = show_body(app, ui, &space, tool_pass(&env.env).as_ref(), win, kind); + if let Some(mut space) = canvas_space(&env.env) { + let mut pass = tool_pass(&env.env); + let bar_paint = PaintSlot::reserve(ui.painter()); + let arc_turn = if kind == BodyKind::Live && app.ui.screen_mode < 3 { + let mut bar_space = space; + if space.wheel().is_some_and(|w| w.claimed || quick_pen_wheel::control_turn(app, &w)) { + bar_space.set_view(given); + } + let bar = quick_pen_bar::quick_pen_bar(app, ui, &bar_space); + quick_pen_wheel::arc_size(app, ui.ctx(), &space, bar) + } else { + false + }; + let bar_shapes = bar_paint.take_after(ui.ctx()); + // The framework settles wheel navigation before the body. A claimed share uses the + // saved view for the controls, painting and tool host, including its first pass. + if arc_turn { + space.set_view(given); + if let Some(pass) = pass.as_mut() { + pass.space = Some(space); + pass.view = Some(given); + } + } + body = with_canvas_space(ui, space, |ui| show_body(app, ui, &space, pass.as_ref(), win, kind, bar_shapes)); + body.arc_turn = arc_turn; } }); let output = shown.output; @@ -289,7 +312,15 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin /// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the /// picture last. -fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { +fn show_body( + app: &mut VectorcraftApp, + ui: &mut Ui, + space: &CanvasSpace, + pass: Option<&ToolPass>, + win: Win, + kind: BodyKind, + bar_shapes: Vec<egui::Shape>, +) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; let background = space.background(); @@ -327,9 +358,7 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O // The bars give way to a drag, not to a click. let dragging = in_gesture(app, ui.ctx()) && ui.input(|i| i.pointer.is_decidedly_dragging()); let task_bar = (app.ui.task_bar && !revolve_editing(app) && !strip && !dragging).then(|| task_bar::task_bar(app, ui, space)).flatten(); - let bar = quick_pen_bar::quick_pen_bar(app, ui, space); - // A Ctrl-wheel turn with the Quick Pen tool changes its arc size; the view stays as it was before the pass. - out.arc_turn = quick_pen_wheel::arc_size(app, ui.ctx(), space, bar); + PaintSlot::reserve(ui.painter()).extend(ui.ctx(), bar_shapes); contour_bar::contour_bar(app, ui, space); // After the task bar, which the row of character alternates keeps clear of. alternates_bar::alternates_bar(app, ui, space, task_bar); diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs index b66ad3963e..f914413a95 100644 --- a/crates/ui-egui/src/canvas/quick_pen_wheel.rs +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -4,7 +4,7 @@ //! and on macOS alike //! ([Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)). //! VectorCraft's own rules: a mouse wheel turned with Ctrl does the same; a mouse wheel makes one -//! step of 15°, as `[` and `]` do, for each notch (each whole wheel line, at least one for each share +//! step of 15°, as `[` and `]` do, for each net whole wheel line (at least one for each nonzero share //! of wheel motion the canvas reads), and a touchpad makes one step for each wheel line of its //! gesture's motion; up makes the arc larger and down smaller, and sideways motion makes no step //! (with Ctrl on Windows and Linux, where the wheel reaches the canvas as a zoom, sideways motion @@ -39,6 +39,9 @@ fn ctrl_alone(m: Mods, os: Platform) -> bool { /// lines in `zoom_lines`; sideways motion there adds to up and down, as egui's zoom factor does. /// Points of a touchpad or a browser are lines of `line` points. fn lines(wheel: &Wheel, line: f32) -> f32 { + // Wheel exposes only the share's signed totals, without individual events or separate up/down + // counts. Opposite notches in one pass cancel; their order and steps at the arc limits cannot + // be recovered. Count the net lines the framework reports. let d = if wheel.zoom_lines != egui::Vec2::ZERO { wheel.zoom_lines.x + wheel.zoom_lines.y } else if wheel.scroll.y != 0.0 { @@ -63,6 +66,12 @@ fn fine(wheel: &Wheel, lines: f32) -> bool { } } +pub(super) fn control_turn(app: &VectorcraftApp, wheel: &Wheel) -> bool { + let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); + let mods = if fine(wheel, lines(wheel, line)) { wheel.held } else { wheel.mods }; + ctrl_alone(mods, crate::keymap::platform()) +} + /// Whole lines in `v`, toward zero, with [`LINE_SLACK`] for rounding. fn whole(v: f32) -> f32 { (v + LINE_SLACK * v.signum()).trunc() @@ -109,12 +118,11 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ctx: &egui::Context, space: &Ca } let muted = w.modal || app_modal; let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); - let mods = if fine(&w, lines(&w, line)) { w.held } else { w.mods }; let over_bar = w.at.zip(bar).is_some_and(|(at, bar)| bar.contains(at)); let quick_pen = app.session.tool_id() == vectorcraft_tools::quickpen::ID; let mut taken = w.claimed; let mut runs = 0.0; - if quick_pen && !muted && !over_bar && ctrl_alone(mods, crate::keymap::platform()) { + if quick_pen && !muted && !over_bar && control_turn(app, &w) { let mut rest = w.claimed_spent.x; let made = steps(&w, line, &mut rest); // A share of a gesture another scroller owns cannot be claimed; the tool still takes it, as the diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 66ae31f690..b7ad3eb99b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2885,8 +2885,6 @@ font-technology Variable Променливи Continuous Arc Непрекъсната дъга Sharp Corner Arc Дъга с остър ъгъл Flip Arc Обръщане на дъгата - Increase Arc Size Увеличаване на размера на дъгата - Decrease Arc Size Намаляване на размера на дъгата Hide Toolbar Скриване на лентата с инструменти Pin Toolbar Position Закачане на позицията на лентата с инструменти Reset Toolbar Position Нулиране на позицията на лентата с инструменти diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 10fb6d4b59..b125e378f5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4254,8 +4254,6 @@ theme Appearance Izgled Continuous Arc Neprekidni luk Sharp Corner Arc Luk s oštrim uglom Flip Arc Preokreni luk - Increase Arc Size Povećaj veličinu luka - Decrease Arc Size Smanji veličinu luka Hide Toolbar Sakrij traku s alatima Pin Toolbar Position Prikvači položaj trake s alatima Reset Toolbar Position Vrati položaj trake s alatima na početno diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4416321fa2..555080655a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3500,8 +3500,6 @@ digits Malayalam Malaiàlam Continuous Arc Arc continu Sharp Corner Arc Arc de cantonada aguda Flip Arc Inverteix l’arc - Increase Arc Size Augmenta la mida de l’arc - Decrease Arc Size Redueix la mida de l’arc Hide Toolbar Amaga la barra d’eines Pin Toolbar Position Fixa la posició de la barra d’eines Reset Toolbar Position Restableix la posició de la barra d’eines diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9dabe178f2..8d11266cdd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4361,8 +4361,6 @@ theme Appearance Motiv Continuous Arc Plynulý oblouk Sharp Corner Arc Oblouk s ostrým rohem Flip Arc Překlopit oblouk - Increase Arc Size Zvětšit velikost oblouku - Decrease Arc Size Zmenšit velikost oblouku Hide Toolbar Skrýt panel nástrojů Pin Toolbar Position Připnout polohu panelu nástrojů Reset Toolbar Position Obnovit polohu panelu nástrojů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 22cfe3a223..9820804ff0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6932,8 +6932,6 @@ theme Appearance Udseende Continuous Arc Fortløbende bue Sharp Corner Arc Bue med skarpt hjørne Flip Arc Vend bue - Increase Arc Size Øg buestørrelse - Decrease Arc Size Formindsk buestørrelse Hide Toolbar Skjul værktøjslinjen Pin Toolbar Position Fastgør værktøjslinjens placering Reset Toolbar Position Nulstil værktøjslinjens placering diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 01a2aa40ef..d29f3c46c0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2809,8 +2809,6 @@ file-filter Templates Vorlagen Continuous Arc Fortlaufender Bogen Sharp Corner Arc Bogen mit scharfer Ecke Flip Arc Bogen spiegeln - Increase Arc Size Bogengröße erhöhen - Decrease Arc Size Bogengröße verringern Hide Toolbar Werkzeugleiste ausblenden Pin Toolbar Position Position der Werkzeugleiste fixieren Reset Toolbar Position Position der Werkzeugleiste zurücksetzen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 87911e63b0..e4a651342a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2208,8 +2208,6 @@ font-technology Variable Μεταβλητές Continuous Arc Συνεχές τόξο Sharp Corner Arc Τόξο με αιχμηρή γωνία Flip Arc Αναστροφή τόξου - Increase Arc Size Αύξηση μεγέθους τόξου - Decrease Arc Size Μείωση μεγέθους τόξου Hide Toolbar Απόκρυψη γραμμής εργαλείων Pin Toolbar Position Σταθεροποίηση θέσης γραμμής εργαλείων Reset Toolbar Position Επαναφορά θέσης γραμμής εργαλείων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index fb8b534363..008a0b6483 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2847,8 +2847,6 @@ font-technology Variable Variables Continuous Arc Arco continuo Sharp Corner Arc Arco de esquina aguda Flip Arc Voltear arco - Increase Arc Size Aumentar tamaño del arco - Decrease Arc Size Reducir tamaño del arco Hide Toolbar Ocultar barra de herramientas Pin Toolbar Position Fijar posición de la barra de herramientas Reset Toolbar Position Restablecer posición de la barra de herramientas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b53af1e432..ffbeb6f49b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4278,8 +4278,6 @@ theme Appearance Ulkoasu Continuous Arc Jatkuva kaari Sharp Corner Arc Terävän kulman kaari Flip Arc Käännä kaari - Increase Arc Size Suurenna kaaren kokoa - Decrease Arc Size Pienennä kaaren kokoa Hide Toolbar Piilota työkalurivi Pin Toolbar Position Kiinnitä työkalurivin sijainti Reset Toolbar Position Palauta työkalurivin sijainti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 597f36670e..7e03e3b7c4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2835,8 +2835,6 @@ font-technology Variable Variables Continuous Arc Arc continu Sharp Corner Arc Arc à angle vif Flip Arc Retourner l’arc - Increase Arc Size Augmenter la taille de l’arc - Decrease Arc Size Réduire la taille de l’arc Hide Toolbar Masquer la barre d’outils Pin Toolbar Position Épingler la position de la barre d’outils Reset Toolbar Position Réinitialiser la position de la barre d’outils diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 981232e347..497ef4d6d8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2849,8 +2849,6 @@ Continuous Arc સતત આર્ક Sharp Corner Arc તીક્ષ્ણ ખૂણાવાળો આર્ક Flip Arc આર્ક ફ્લિપ કરો - Increase Arc Size આર્કનું કદ વધારો - Decrease Arc Size આર્કનું કદ ઘટાડો Hide Toolbar ટૂલબાર છુપાવો Pin Toolbar Position ટૂલબાર સ્થિતિ પિન કરો Reset Toolbar Position ટૂલબાર સ્થિતિ રીસેટ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 0be240457b..8ad28968c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4047,8 +4047,6 @@ arrowhead Feather पंख Continuous Arc सतत आर्क Sharp Corner Arc तीखे कोने वाला आर्क Flip Arc आर्क पलटें - Increase Arc Size आर्क का आकार बढ़ाएँ - Decrease Arc Size आर्क का आकार घटाएँ Hide Toolbar टूलबार छिपाएँ Pin Toolbar Position टूलबार स्थिति पिन करें Reset Toolbar Position टूलबार स्थिति रीसेट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d9d282b649..3116815efa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3379,8 +3379,6 @@ file-filter Templates Sablonok Continuous Arc Folytonos ív Sharp Corner Arc Éles sarkú ív Flip Arc Ív tükrözése - Increase Arc Size Ívméret növelése - Decrease Arc Size Ívméret csökkentése Hide Toolbar Eszköztár elrejtése Pin Toolbar Position Eszköztár helyének rögzítése Reset Toolbar Position Eszköztár helyének visszaállítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e7c8d8be4a..b159d2bfb7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4797,8 +4797,6 @@ theme Appearance Tampilan Continuous Arc Busur bersambung Sharp Corner Arc Busur sudut tajam Flip Arc Balik busur - Increase Arc Size Perbesar ukuran busur - Decrease Arc Size Perkecil ukuran busur Hide Toolbar Sembunyikan bilah alat Pin Toolbar Position Sematkan posisi bilah alat Reset Toolbar Position Atur ulang posisi bilah alat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 57601c82df..d6b341a367 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2894,8 +2894,6 @@ file-filter Templates Modelli Continuous Arc Arco continuo Sharp Corner Arc Arco ad angolo vivo Flip Arc Capovolgi arco - Increase Arc Size Aumenta dimensione arco - Decrease Arc Size Riduci dimensione arco Hide Toolbar Nascondi barra degli strumenti Pin Toolbar Position Fissa posizione barra degli strumenti Reset Toolbar Position Ripristina posizione barra degli strumenti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 681efb5f1b..48f6dd36cf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2972,8 +2972,6 @@ antiAlias Sharp シャープ Continuous Arc 連続円弧 Sharp Corner Arc 鋭角円弧 Flip Arc 円弧を反転 - Increase Arc Size 円弧のサイズを大きく - Decrease Arc Size 円弧のサイズを小さく Hide Toolbar ツールバーを隠す Pin Toolbar Position ツールバーの位置を固定 Reset Toolbar Position ツールバーの位置をリセット diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 646108c76d..cbb58ee5ab 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6101,8 +6101,6 @@ theme Appearance იერსახე Continuous Arc უწყვეტი რკალი Sharp Corner Arc მახვილკუთხიანი რკალი Flip Arc რკალის არეკვლა - Increase Arc Size რკალის ზომის გაზრდა - Decrease Arc Size რკალის ზომის შემცირება Hide Toolbar ხელსაწყოთა ზოლის დამალვა Pin Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამაგრება Reset Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამოყრა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4dffe2d723..bd430d2fc1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2962,8 +2962,6 @@ antiAlias Sharp 날카롭게 Continuous Arc 연속 호 Sharp Corner Arc 뾰족한 모서리 호 Flip Arc 호 뒤집기 - Increase Arc Size 호 크기 늘리기 - Decrease Arc Size 호 크기 줄이기 Hide Toolbar 도구 모음 숨기기 Pin Toolbar Position 도구 모음 위치 고정 Reset Toolbar Position 도구 모음 위치 재설정 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 06535d7ea7..20365f1488 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4793,8 +4793,6 @@ theme Appearance Vormgeving Continuous Arc Doorlopende boog Sharp Corner Arc Boog met scherpe hoek Flip Arc Boog spiegelen - Increase Arc Size Boog groter maken - Decrease Arc Size Boog kleiner maken Hide Toolbar Werkbalk verbergen Pin Toolbar Position Werkbalkpositie vastzetten Reset Toolbar Position Werkbalkpositie herstellen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fc2e60066f..4a22a1dd93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4224,8 +4224,6 @@ theme Appearance Wygląd Continuous Arc Łuk ciągły Sharp Corner Arc Łuk z ostrym narożnikiem Flip Arc Odwróć łuk - Increase Arc Size Zwiększ rozmiar łuku - Decrease Arc Size Zmniejsz rozmiar łuku Hide Toolbar Ukryj pasek narzędzi Pin Toolbar Position Przypnij położenie paska narzędzi Reset Toolbar Position Resetuj położenie paska narzędzi diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7ccf71dad0..6d910ce85f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2337,8 +2337,6 @@ antiAlias Sharp Nítido Continuous Arc Arco Contínuo Sharp Corner Arc Arco de Canto Agudo Flip Arc Virar Arco - Increase Arc Size Aumentar Tamanho do Arco - Decrease Arc Size Diminuir Tamanho do Arco Hide Toolbar Ocultar Barra de Ferramentas Pin Toolbar Position Fixar Posição da Barra de Ferramentas Reset Toolbar Position Redefinir Posição da Barra de Ferramentas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1d662a491c..60906af64a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2876,8 +2876,6 @@ file-filter Templates Шаблоны Continuous Arc Непрерывная дуга Sharp Corner Arc Дуга с острым углом Flip Arc Отразить дугу - Increase Arc Size Увеличить размер дуги - Decrease Arc Size Уменьшить размер дуги Hide Toolbar Скрыть панель инструментов Pin Toolbar Position Закрепить положение панели инструментов Reset Toolbar Position Сбросить положение панели инструментов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 0c739b14d6..bf7420d255 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2768,8 +2768,6 @@ font-technology Variable Variabla Continuous Arc Kontinuerlig båge Sharp Corner Arc Båge med skarpt hörn Flip Arc Vänd båge - Increase Arc Size Öka bågstorlek - Decrease Arc Size Minska bågstorlek Hide Toolbar Dölj verktygsfältet Pin Toolbar Position Fäst verktygsfältets position Reset Toolbar Position Återställ verktygsfältets position diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ad7f1cc97f..830b60e56b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2611,8 +2611,6 @@ shape Open Açık Continuous Arc Sürekli Yay Sharp Corner Arc Keskin Köşeli Yay Flip Arc Yayı Çevir - Increase Arc Size Yay Boyutunu Artır - Decrease Arc Size Yay Boyutunu Azalt Hide Toolbar Araç Çubuğunu Gizle Pin Toolbar Position Araç Çubuğu Konumunu Sabitle Reset Toolbar Position Araç Çubuğu Konumunu Sıfırla diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d898b8991b..09a9e4bf6d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2886,8 +2886,6 @@ file-filter Templates Шаблони Continuous Arc Неперервна дуга Sharp Corner Arc Дуга з гострим кутом Flip Arc Відобразити дугу - Increase Arc Size Збільшити розмір дуги - Decrease Arc Size Зменшити розмір дуги Hide Toolbar Сховати панель інструментів Pin Toolbar Position Закріпити положення панелі інструментів Reset Toolbar Position Скинути положення панелі інструментів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a04c6480be..bc63725d0f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3199,8 +3199,6 @@ digits Hindi Hindi Continuous Arc Cung liên tục Sharp Corner Arc Cung góc nhọn Flip Arc Lật cung - Increase Arc Size Tăng kích thước cung - Decrease Arc Size Giảm kích thước cung Hide Toolbar Ẩn thanh công cụ Pin Toolbar Position Ghim vị trí thanh công cụ Reset Toolbar Position Đặt lại vị trí thanh công cụ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c69caa23bf..9b7e1c7bbc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2737,8 +2737,6 @@ file-filter Templates 模板 Continuous Arc 连续弧线 Sharp Corner Arc 尖角弧线 Flip Arc 翻转弧线 - Increase Arc Size 增大弧线尺寸 - Decrease Arc Size 减小弧线尺寸 Hide Toolbar 隐藏工具栏 Pin Toolbar Position 固定工具栏位置 Reset Toolbar Position 重置工具栏位置 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 99cdf242e6..2e3bae2d60 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4197,8 +4197,6 @@ liquify-list-end {0}, {1} {0}和{1} Continuous Arc 連續弧線 Sharp Corner Arc 尖角弧線 Flip Arc 翻轉弧線 - Increase Arc Size 增大弧線尺寸 - Decrease Arc Size 減小弧線尺寸 Hide Toolbar 隱藏工具列 Pin Toolbar Position 釘選工具列位置 Reset Toolbar Position 重設工具列位置 diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs index 369e27847d..dba5367ebe 100644 --- a/crates/ui-egui/src/tests/quickpenwheel.rs +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -134,6 +134,51 @@ fn ctrl_wheel_changes_the_arc_size_and_not_the_view() { }); } +/// The first claimed share keeps both the stored view and the tool host's document point. +#[test] +fn the_first_ctrl_wheel_frame_keeps_the_view_and_pointer() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let at = center(rig) + vec2(80.0, 40.0); + rig.fx.frame(vec![Event::PointerMoved(at)]); + let still = view(rig); + let point = rig.app().hover_doc.expect("the pointer is over the canvas"); + let win = crate::doc_windows::current(&rig.app()).unwrap(); + let id = crate::canvas::canvas_id(win); + let shown = craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view; + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_eq!(view(rig).zoom, still.zoom, "the first share keeps the zoom"); + assert_eq!(view(rig).center, still.center, "the first share keeps the pan"); + assert_eq!(craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view, shown, "the tool host sees the saved view"); + assert_eq!(rig.app().hover_doc, Some(point), "the tool host uses the saved view in the same frame"); + }); +} + +/// Opposite notches in one frame use the framework's net lines and keep the tool host's view. +#[test] +fn opposite_notches_use_the_frameworks_reported_net_motion() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + rig.fx.frame(vec![Event::PointerMoved(center(rig) + vec2(80.0, 40.0))]); + let win = crate::doc_windows::current(&rig.app()).unwrap(); + let id = crate::canvas::canvas_id(win); + let shown = craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view; + for (start, notches, expected) in + [(345, vec![1.0, -1.0], 345.0), (345, vec![1.0, 1.0, -1.0], 345.0), (180, vec![1.0, -1.0], 180.0), (180, vec![1.0, 1.0, -1.0], 195.0)] + { + rig.app().run("tool.setOption", json!({"key": "turn", "value": start})).unwrap(); + rig.fx.frame(notches.into_iter().map(|dy| notch(dy, ctrl())).collect()); + assert_eq!(arc_size(rig), expected, "the framework reports net lines, including at the arc limit"); + assert_eq!(craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view, shown, "mixed notches keep the tool host's view"); + rig.fx.advance(1.5); + rig.fx.frame(vec![]); + } + }); +} + /// A touchpad steps once per wheel line of motion: half a line makes no step, the second half of the /// same gesture makes one, and momentum after it makes none (egui reports momentum on macOS). Half a /// line in a later turn does not add to the half before it. diff --git a/docs/mcp.md b/docs/mcp.md index 161289dff3..7cf9cd99f6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8841,9 +8841,12 @@ tool edit, then returns false, changing nothing more, when the Quick Pen tool is scroll on a touchpad over the canvas (the Control key on macOS too) changes the arc size as well, as [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) lists: the touchpad makes one step for each wheel line of its motion, and motion that goes on after the fingers lift -makes none. A mouse wheel turned with Ctrl over the canvas does the same, one step for each wheel event (one per -notch). Up makes the arc size larger and down smaller, sideways motion makes no step, and the view does not zoom or -scroll for the rest of that wheel turn. During a drag, C, `[` `]` and the wheel change the sharp-corner arc being +makes none. A mouse wheel turned with Ctrl over the canvas does the same, one step for each net whole wheel line +reported by the canvas framework, with at least one step for a nonzero share. The framework sums events within a +frame, so opposite notches cancel and their order is unavailable. Up makes the arc size larger and down smaller. +Sideways motion makes no step, except when Ctrl on Windows or Linux makes the framework report it as zoom motion. +The view does not zoom or scroll for the rest of that wheel turn. During a drag, +C, `[` `]` and the wheel change the sharp-corner arc being dragged, and Alt switches its action. A dragged piece ends where the press is let go. A click on the first point closes the path, and a click on an end of an open path goes on drawing from that end. Escape or Enter ends the path, and so does an edit made to it by another command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit @@ -8852,7 +8855,7 @@ command edits the document adds no piece, and the edit stays. The path's points preview shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step, together with the flips and size changes made during its drag, and each flip or size change made between presses is one undo step. The arc size of 180°, its 15° steps, the side an arc bulges to, what C, `[` `]` and the wheel do during a drag, Enter -ending the path, the mouse wheel changing the arc size, and the wheel's step per event or wheel line and its direction are +ending the path, the mouse wheel changing the arc size, and the wheel's step per net wheel line and its direction are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). From 9a843a5f0ef8d05ea4dc3b6159922712b6675dde Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 29 Nov 2026 22:58:22 -0800 Subject: [PATCH 21/71] Quick Pen: the arc-size wheel keeps other view changes and pinches A Ctrl+wheel share the tool takes now restores only the zoom, pan and rotation from before the wheel, so the content rect beside the rulers stays as the canvas settled it and a view command queued in the same frame still applies. A share outside the content rect makes no step, a native pinch with Control held zooms as usual, and the toolbar is shown in the restored space. The parity entry says one step per net whole wheel line. --- crates/ui-egui/src/canvas.rs | 30 +++++--- crates/ui-egui/src/canvas/quick_pen_wheel.rs | 7 +- crates/ui-egui/src/tests/quickpenwheel.rs | 75 ++++++++++++++++++++ docs/target-app-parity.md | 2 +- 4 files changed, 100 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f6ac38176b..85ad06e131 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -145,7 +145,7 @@ struct Body { /// A view a compass or scroll bar edit made this pass. edited: Option<CanvasView>, /// The Quick Pen tool took this pass's wheel for its arc size ([`quick_pen_wheel::arc_size`]). - arc_turn: bool, + arc_view: Option<CanvasView>, } /// Window `win`'s document in the framework canvas, filling the rest of `ui`. True when the canvas @@ -211,6 +211,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // cursors the tools are told about. let precise = app.precise_cursors() != host_caps_lock; let prefs = &app.session.prefs; + let before_wheel = cv; let mut canvas = Canvas::new("Document") .id(canvas_id(win)) .view(Bind::bound(&mut cv)) @@ -235,12 +236,21 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin if let Some(mut space) = canvas_space(&env.env) { let mut pass = tool_pass(&env.env); let bar_paint = PaintSlot::reserve(ui.painter()); + let mut arc_view = space.target(); + if space.wheel().is_some_and(|w| !w.claimed && quick_pen_wheel::control_turn(app, &w)) { + arc_view.zoom = before_wheel.zoom; + arc_view.center = before_wheel.center; + arc_view.rotation = before_wheel.rotation; + for request in &queued { + request.command().apply(&mut arc_view, &target, Some(&layers), ppp, &scheme); + } + } let arc_turn = if kind == BodyKind::Live && app.ui.screen_mode < 3 { let mut bar_space = space; if space.wheel().is_some_and(|w| w.claimed || quick_pen_wheel::control_turn(app, &w)) { - bar_space.set_view(given); + bar_space.set_view(arc_view); } - let bar = quick_pen_bar::quick_pen_bar(app, ui, &bar_space); + let bar = with_canvas_space(ui, bar_space, |ui| quick_pen_bar::quick_pen_bar(app, ui, &bar_space)); quick_pen_wheel::arc_size(app, ui.ctx(), &space, bar) } else { false @@ -249,14 +259,14 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // The framework settles wheel navigation before the body. A claimed share uses the // saved view for the controls, painting and tool host, including its first pass. if arc_turn { - space.set_view(given); + space.set_view(arc_view); if let Some(pass) = pass.as_mut() { pass.space = Some(space); - pass.view = Some(given); + pass.view = Some(arc_view); } } body = with_canvas_space(ui, space, |ui| show_body(app, ui, &space, pass.as_ref(), win, kind, bar_shapes)); - body.arc_turn = arc_turn; + body.arc_view = arc_turn.then_some(arc_view); } }); let output = shown.output; @@ -269,7 +279,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, context_key, edited, arc_turn } = body; + let Body { reply, context_at, context_key, edited, arc_view } = body; let request = reply .as_ref() .and_then(|r| r.context.as_ref()) @@ -277,13 +287,11 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin .or(context_at.map(|at| context_menu::Request { at, key: context_key })); let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own, and a - // wheel turn the Quick Pen tool takes for its arc size keeps the view the pass began with. + // wheel turn the Quick Pen tool takes for its arc size leaves other view requests in place. let view_now = if presenting && ui.input(|i| i.pointer.middle_down()) { given - } else if arc_turn { - edited.unwrap_or(given) } else { - edited.or(reply.and_then(|r| r.view)).or(output.view).unwrap_or(cv) + edited.or(reply.and_then(|r| r.view)).or(arc_view).or(output.view).unwrap_or(cv) }; if let Some(view) = doc_windows::view_mut(app, win) { view.set_canvas(&view_now, scaling); diff --git a/crates/ui-egui/src/canvas/quick_pen_wheel.rs b/crates/ui-egui/src/canvas/quick_pen_wheel.rs index f914413a95..96616e3b1d 100644 --- a/crates/ui-egui/src/canvas/quick_pen_wheel.rs +++ b/crates/ui-egui/src/canvas/quick_pen_wheel.rs @@ -69,7 +69,9 @@ fn fine(wheel: &Wheel, lines: f32) -> bool { pub(super) fn control_turn(app: &VectorcraftApp, wheel: &Wheel) -> bool { let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); let mods = if fine(wheel, lines(wheel, line)) { wheel.held } else { wheel.mods }; - ctrl_alone(mods, crate::keymap::platform()) + let scrolling = + (wheel.scroll.is_finite() && wheel.scroll != egui::Vec2::ZERO) || (wheel.zoom_lines.is_finite() && wheel.zoom_lines != egui::Vec2::ZERO); + ctrl_alone(mods, crate::keymap::platform()) && (wheel.claimed || scrolling) } /// Whole lines in `v`, toward zero, with [`LINE_SLACK`] for rounding. @@ -119,10 +121,11 @@ pub(super) fn arc_size(app: &mut VectorcraftApp, ctx: &egui::Context, space: &Ca let muted = w.modal || app_modal; let line = crate::app::view::navigation(&app.session.prefs).wheel_line.max(1.0); let over_bar = w.at.zip(bar).is_some_and(|(at, bar)| bar.contains(at)); + let over_content = w.at.is_some_and(|at| space.view.rect.contains(at)); let quick_pen = app.session.tool_id() == vectorcraft_tools::quickpen::ID; let mut taken = w.claimed; let mut runs = 0.0; - if quick_pen && !muted && !over_bar && control_turn(app, &w) { + if quick_pen && !muted && !over_bar && over_content && control_turn(app, &w) { let mut rest = w.claimed_spent.x; let made = steps(&w, line, &mut rest); // A share of a gesture another scroller owns cannot be claimed; the tool still takes it, as the diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs index dba5367ebe..98c3a82e13 100644 --- a/crates/ui-egui/src/tests/quickpenwheel.rs +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -2,6 +2,7 @@ //! is; the arc size commands step it as `[` and `]` do. use craft::behavior::CanvasView; +use craft::ui::canvas::{ViewCommands, ViewRequest}; use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, Pos2, TouchPhase, vec2}; use serde_json::json; use vectorcraft_doc::NodeKind; @@ -138,6 +139,7 @@ fn ctrl_wheel_changes_the_arc_size_and_not_the_view() { #[test] fn the_first_ctrl_wheel_frame_keeps_the_view_and_pointer() { let mut app = app(); + app.ui.view.rulers = true; on_canvas(&mut app, |rig| { rig.fx.settle(); let at = center(rig) + vec2(80.0, 40.0); @@ -151,11 +153,84 @@ fn the_first_ctrl_wheel_frame_keeps_the_view_and_pointer() { assert_eq!(arc_size(rig), 195.0); assert_eq!(view(rig).zoom, still.zoom, "the first share keeps the zoom"); assert_eq!(view(rig).center, still.center, "the first share keeps the pan"); + assert_eq!(view(rig).rect, still.rect, "the content stays inside the rulers"); assert_eq!(craft::ui::canvas::ToolHost::shown_space(rig.fx.ctx(), id).unwrap().view, shown, "the tool host sees the saved view"); assert_eq!(rig.app().hover_doc, Some(point), "the tool host uses the saved view in the same frame"); }); } +#[test] +fn a_queued_fit_survives_the_first_ctrl_wheel_frame() { + let mut app = app(); + app.session.prefs.animated_zoom = false; + on_canvas(&mut app, |rig| { + rig.fx.settle(); + let fitted = view(rig); + rig.app().run("view.zoomIn", json!({})).unwrap(); + rig.fx.settle(); + assert_ne!(view(rig).zoom, fitted.zoom); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + rig.app().request_view(ViewRequest::Command(ViewCommands::FitArtboard), None); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_eq!(view(rig), fitted, "the queued fit reaches the stored view in the same frame"); + }); +} + +#[test] +fn the_toolbar_keeps_its_anchor_on_the_first_ctrl_wheel_frame() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + click_doc(rig, 100.0, 150.0); + rig.fx.settle(); + let bar = rig.target("Quick Pen").unwrap().rect; + rig.fx.frame(vec![Event::PointerMoved(center(rig) + vec2(-120.0, -80.0))]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + assert_eq!(rig.target("Quick Pen").unwrap().rect, bar, "the toolbar maps its anchor through the saved space"); + }); +} + +#[test] +fn a_claimed_wheel_makes_no_step_outside_the_content() { + let mut app = app(); + app.ui.view.rulers = true; + on_canvas(&mut app, |rig| { + rig.fx.settle(); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + let still = view(rig); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0); + let outside = egui::pos2(still.rect.left() - 1.0, still.rect.center().y); + rig.fx.frame(vec![Event::PointerMoved(outside)]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 195.0, "a share over a ruler makes no step"); + assert_eq!(view(rig), still, "the claimed gesture still keeps the view"); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + rig.fx.frame(vec![notch(1.0, ctrl())]); + assert_eq!(arc_size(rig), 210.0, "the gesture resumes inside the content"); + }); +} + +#[test] +fn a_native_pinch_with_control_zooms_the_view() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.fx.settle(); + rig.fx.hold(ctrl()); + rig.fx.frame(vec![Event::PointerMoved(center(rig))]); + let still = view(rig); + rig.fx.frame(vec![Event::Zoom(1.25)]); + assert!(view(rig).zoom > still.zoom, "a native pinch keeps its zoom"); + assert_eq!(arc_size(rig), 180.0); + let zoomed = view(rig); + rig.fx.frame(vec![Event::Zoom(1.25)]); + assert!(view(rig).zoom > zoomed.zoom, "the pinch was not claimed as an arc gesture"); + rig.fx.hold(Modifiers::NONE); + }); +} + /// Opposite notches in one frame use the framework's net lines and keep the tool host's view. #[test] fn opposite_notches_use_the_frameworks_reported_net_motion() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cbf285df6c..4928ac34a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -706,7 +706,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen editing (#2660):** with no path being drawn, the Quick Pen tool moves an anchor or a segment of a selected path by a drag (`path.moveAnchors` with `interpolate`, one undo step; beside a moved corner anchor a line stays a line and an arc an arc, and at a moved smooth anchor the handles stay in line and the segments bend to meet), selects an anchor with a click and adds one with Shift-click, and the canvas context menu's Delete removes the selected anchors (`edit.clear`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. Which presses select and which move, and the drag snapping only an anchor, are VectorCraft's own rules. Tests: tools `quickpen::tests::a_selected_paths_anchors_and_segments_show_the_edit_cursors`, engine `tests::quickpen` (`a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc`, `a_drag_on_a_segment_moves_its_ends`, `a_drag_on_an_open_end_moves_it`, `a_release_past_the_drag_distance_moves_the_anchor`, `clicks_select_anchors_for_delete`, `escape_takes_back_an_anchor_drag`, `a_press_while_drawing_adds_a_piece`), ui-egui `tests::contextmenu::the_quick_pen_menu_deletes_the_selected_anchors`. Score and hours unchanged. - **Recolor with Preset asks for a library first:** Edit › Edit Colors › Recolor with Preset (1, 2 and 3 Color Job, Color Library) opens a Recolor with Preset dialog whose Limit to Library menu (None, Document Swatches or a library) is applied when Recolor Artwork opens (<https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=251>, "Quickly reduce colors using a preset"). A 1 Color Job limited to the document's swatches with a spot or global ink picked turns gray art into tints of that ink linked to its swatch, so editing the swatch recolors the art. Tests `recolor_with_preset_asks_for_a_library_first` and `a_one_color_job_limited_to_document_swatches_links_gray_art_to_the_ink`. Area score and hours unchanged. -- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` and Ctrl with a touchpad scroll or a mouse wheel over the canvas change the arc size by 15° (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`), a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, C, `[` and `]` changing the arc being dragged, the mouse wheel changing the arc size, and one step per wheel event of a mouse wheel are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `tests::quickpenwheel`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. +- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` and Ctrl with a touchpad scroll or a mouse wheel over the canvas change the arc size by 15° (`tool.quickPen.arcLarger`, `tool.quickPen.arcSmaller`), a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, C, `[` and `]` changing the arc being dragged, the mouse wheel changing the arc size, and one step per net whole wheel line of a mouse wheel are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `tests::quickpenwheel`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. From f5962eb16158d9ebec028b9df05ca3a06cd1340d Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:32:27 +0530 Subject: [PATCH 22/71] A right-click on a Glyphs cell inserts or applies that glyph. The menu item does what a double-click does, and stays disabled when the glyph cannot be applied. Co-authored-by: Cursor <cursoragent@cursor.com> --- crates/ui-egui/src/panels/glyphs.rs | 35 +++++++- crates/ui-egui/src/panels/glyphs/tests.rs | 101 ++++++++++++++++++++++ docs/gaps.md | 2 + 3 files changed, 134 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index e639ae3ea4..4d60dd59ef 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -15,6 +15,8 @@ //! as one of its alternates in its word. A glyph no feature reaches whose name does not belong to //! another letter is applied as a glyph choice, which may not join. Other glyphs are drawn dimmed, //! and their notes say why they cannot be applied to the selection. +//! A right-click on a character offers Insert Glyph. A right-click on a glyph without a +//! character offers Apply Alternate. Both use the same text target as double-click or Enter. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`menu_rows`]). //! After the framework's categories, the Show menu lists the OpenType categories the browsed font @@ -24,10 +26,10 @@ use std::collections::HashSet; use std::sync::Arc; -use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsWords}; +use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; use craft::keymap::CommandRef; -use craft::ui::contract::Bind; -use craft::ui::menu::PanelRow; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Env; use egui::{Color32, ColorImage, Ui}; @@ -483,7 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - if let Some(cell) = out.activated { + let menu_cell = out + .menu + .as_ref() + .filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)) + .map(|menu| menu.cell); + if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } if let Some(pick) = out.alternate { @@ -491,6 +498,26 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Offer the action for the clicked cell using the grid's face and text context for this pass. +fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphCellMenu) -> bool { + let Some(face) = &source.face else { return false }; + let (label, enabled) = match menu.cell { + GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), + GlyphCell::Glyph(gid) => { + let applies = match &source.listing { + Some(listing) => listing.variants.iter().any(|variant| variant.gid == gid), + None => source.fit.as_ref().is_some_and(|fit| fit.pick(face, gid).is_some()), + }; + (tl!("Apply Alternate"), applies) + } + _ => return false, + }; + Menu::context(label, &menu.opener) + .show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran) + .inner + .unwrap_or(false) +} + /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation /// form), or put the glyph on the selected character. pub(crate) fn activate(app: &mut VectorcraftApp, cell: GlyphCell) { diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index 0886975276..a4f6635324 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -1102,3 +1102,104 @@ fn the_grid_lists_the_same_cells_from_the_character_list_read_once() { assert!(list.iter().all(|c| matches!(c, GlyphCell::Glyph(_))), "no character is listed"); assert!(!list.is_empty(), "the glyphs are listed by glyph id"); } + +/// The name a glyph-id cell shows, as the grid names it. +fn glyph_cell_name(face: &vectorcraft_text::FontFace, gid: u32) -> String { + let name = face.glyph_name(gid).unwrap_or_else(|| format!("gid {gid}")); + format!("{name}, glyph {gid}") +} + +/// A right-click on an encoded cell offers Insert Glyph, and choosing it inserts that character in one undo step. +#[test] +fn right_clicking_a_glyph_cell_offers_insert_glyph() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let (mut app, id) = editing("a"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": ALIASED_JOINING_FAMILY})).unwrap(); + select(&mut app, 1, 1); + crate::panels::character::end_typing(&mut app); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(panel.menu_item_enabled("Insert Glyph")); + assert!(!panel.shows("Apply Alternate"), "a character cell offers Insert Glyph"); + panel.click_menu_item("Insert Glyph"); + { + let mut app = panel.app(); + crate::panels::character::end_typing(&mut app); + } + let app = panel.app(); + assert_eq!(plain_of(&app, id), "aB"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(plain_of(&panel.app(), id), "a"); +} + +#[test] +fn insert_glyph_is_disabled_without_a_text_target() { + use vectorcraft_text::test_fonts::{ALIASED_JOINING_FAMILY, aliased_joining_font}; + FontDb::global().add_font(aliased_joining_font().expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.ui.glyphs_font = Some((ALIASED_JOINING_FAMILY.to_string(), "Regular".to_string())); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click("B, U+0042"); + assert!(!panel.menu_item_enabled("Insert Glyph")); +} + +/// In Alternates for Selection a right-click offers Apply Alternate in one undo step. +#[test] +fn right_clicking_an_alternate_cell_offers_apply_alternate() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + show_category(&mut app, "Alternates for Selection"); + let list = listed(&mut app, "Alternates for Selection"); + let GlyphCell::Glyph(gid) = list[2] else { panic!("an alternate is a glyph") }; + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let name = glyph_cell_name(&face, gid); + let undo = undo_len(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(panel.menu_item_enabled("Apply Alternate")); + assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(glyph_ids(&app, &json!(id)), [g('B'), g('x'), g('M')]); + drop(app); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&panel.app(), &json!(id)), [g('B'), g('u'), g('M')]); +} + +/// A glyph a double-click would only explain has a disabled menu item, and choosing it changes nothing. +#[test] +fn a_glyph_that_cannot_be_applied_disables_the_menu_item() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let (mut app, id) = editing("\u{0627}"); + let id = id.as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 0, 2); + show_category(&mut app, "stylisticAlternates"); + let gid = u32::from(source_sans_gid('w').expect("a glyph")); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + assert!(cell_info(&mut app, GlyphCell::Glyph(gid)).dimmed, "w is not an alternate of alef"); + let name = glyph_cell_name(&face, gid); + let (undo, status, plain) = (undo_len(&app), app.ui.status.clone(), glyph_ids(&app, &json!(id))); + let mut panel = crate::tests::panel_harness::Panel::new(app, super::show); + panel.secondary_click(&name); + assert!(!panel.menu_item_enabled("Apply Alternate")); + panel.click_menu_item("Apply Alternate"); + let app = panel.app(); + assert_eq!(glyph_ids(&app, &json!(id)), plain); + assert_eq!(undo_len(&app), undo); + assert_eq!(app.ui.status, status); +} diff --git a/docs/gaps.md b/docs/gaps.md index 35587afab4..02049a64b7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -551,6 +551,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. + - **Implemented and tested (2026-11-21):** Properties panel Quick Actions follow every selected object. Ungroup (`object.ungroup`) is offered when any selected object is a group, including several groups, a group selected after a path, and a group that holds another group. Isolate Group (`object.isolate`) is offered only when that one group is the whole selection. Unite (`object.pathfinder.unite`) appears only for selections of at least two objects, each a non-guide path or a compound path. It appears alongside Group and Make Clipping Mask. Headless regressions: `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group` and `several_paths_offer_group_clipping_mask_and_unite`. Other G12 gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-21):** Document Info's panel menu Selection Only (`ui.docInfo.selectionOnly`; kept in memory for the session, not stored) asks `document.info` for the selection: object counts cover the selected nodes and their descendants, and with no artwork selected it shows `(No artwork selected)` instead of the document's counts, while artboards the Artboard tool has selected still show under Document. With the item off, counts stay for the whole document. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard` and `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. From d7686cd9f40b8ba8b4a9a36f56e5c592b86e230f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 30 Nov 2026 20:15:53 -0800 Subject: [PATCH 23/71] Fix #10262: Document Info scrolls in a short dock group Document Info was left out of the panel forms that scroll inside their dock group, so in a short group its lower rows could not be reached. It now scrolls like the other forms. A test draws every panel in 120 pt and 60 pt groups and scrolls each one until its lowest control is in view. --- crates/ui-egui/src/dock.rs | 1 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/panel_harness.rs | 14 ++++++ crates/ui-egui/src/tests/panel_scroll.rs | 61 +++++++++++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 crates/ui-egui/src/tests/panel_scroll.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index dcff2191a4..d5f31df6c3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -22,6 +22,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { | "blend" | "character" | "color" + | "docInfo" | "magicWand" | "openType" | "paragraph" diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 70eba60a17..953946dc7f 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -23,6 +23,7 @@ mod numfields; mod overprint; mod paintchips; pub(crate) mod panel_harness; +mod panel_scroll; mod pastechords; mod pathtype; mod pdfoutput; diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 60e6bd2182..0b9fa40f9f 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -383,6 +383,20 @@ impl Panel { seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0) } + /// The named control the latest frame lays out lowest, where its name finds that control: the control a reader + /// reaches last. + pub(crate) fn lowest(&self) -> Option<String> { + let mut names = self.names(); + names.sort(); + names.dedup(); + names + .into_iter() + .filter_map(|name| self.fixture.by_label(&name).map(|t| (name, t.rect.bottom()))) + .filter(|(_, bottom)| bottom.is_finite()) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(name, _)| name) + } + /// Whether the control named `name` takes input. pub(crate) fn enabled(&self, name: &str) -> bool { !self.fixture.tree().is_disabled_key(self.look(name).node) diff --git a/crates/ui-egui/src/tests/panel_scroll.rs b/crates/ui-egui/src/tests/panel_scroll.rs new file mode 100644 index 0000000000..0fbc73e271 --- /dev/null +++ b/crates/ui-egui/src/tests/panel_scroll.rs @@ -0,0 +1,61 @@ +//! Every panel in a dock group shorter than its contents scrolls to its last control (#10262). + +use std::cell::RefCell; + +use egui::{Ui, pos2, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; + +thread_local! { + /// The panel the harness draws. + static SHOWN: RefCell<String> = const { RefCell::new(String::new()) }; +} + +fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + let id = SHOWN.with(|s| s.borrow().clone()); + crate::dock::panel_body(app, ui, &id); +} + +/// The panels whose last control a short dock group hides and the wheel does not bring into view. +fn unreachable_panels(room_height: f32) -> Vec<String> { + let mut stuck = Vec::new(); + for (id, _) in crate::state::all_panels() { + SHOWN.with(|s| *s.borrow_mut() = id.to_owned()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + if let Err(e) = app.run("file.new", json!({"width": 200, "height": 200})) { + panic!("file.new: {e}"); + } + // A selected path, so the panels that edit a selection show their controls. + if let Err(e) = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})) { + panic!("shape.rectangle: {e}"); + } + let mut panel = Panel::new(app, draw); + let Some(last) = panel.lowest() else { continue }; + panel.room(vec2(300.0, room_height)); + panel.frame(); + panel.frame(); + if !panel.shows(&last) || panel.in_view(&last) { + continue; + } + for _ in 0..60 { + panel.scroll_at(pos2(150.0, room_height / 2.0), -120.0); + if panel.in_view(&last) { + break; + } + } + if !panel.in_view(&last) { + stuck.push(format!("{id}: {last:?}")); + } + } + stuck +} + +#[test] +fn every_panel_in_a_short_dock_group_scrolls_to_its_last_control() { + let mut stuck = unreachable_panels(120.0); + stuck.extend(unreachable_panels(60.0)); + assert!(stuck.is_empty(), "panels whose last control the wheel cannot reach: {stuck:?}"); +} From e880f695a23ad838b9bf4b9db1a7c9e4391539eb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 30 Nov 2026 20:40:26 -0800 Subject: [PATCH 24/71] New Document: Preset Details rows stand a stack gap apart The Preset Details rows stood a tight gap apart, so each caption touched the field above it. craft-libs now lays them out a stack gap apart, with a fixed details column and Create and Close at its foot (storytold/ craft-libs e93e6f62a and e433cdfa8). The pin moves to craft-libs main 26f293d78, which holds both; the egui and winit revisions are unchanged. - More Settings and Manage Profiles stand side by side, each as wide as its words, instead of two buttons across the whole column. - The pin brings two API changes: CanvasScrollbars::clear_of takes ShownBars, and a LegacyFile lists its paths and parses one slot per path. - Accessible names now read a line break as a space, so the Color Wheel document-color tests name a swatch "#0000ff Used 1 time". - The small-window test accepts the Bleed fields in one row when the fixed column holds them. --- Cargo.lock | 173 +++++++++--------- Cargo.toml | 76 ++++---- apps/vectorcraft-web/Cargo.toml | 2 +- apps/vectorcraft/src/prefs.rs | 13 +- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/dialogs/new_document.rs | 74 ++++++-- .../tests_color_wheel_document_colors.rs | 3 +- 7 files changed, 204 insertions(+), 141 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 772196967a..c831102d13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,9 +2165,10 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", + "craft-font-catalog", "craft-i18n", "craft-keymap", "craft-theme", @@ -2181,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "accesskit", "craft-behavior", @@ -2219,7 +2220,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2230,7 +2231,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-host", @@ -2248,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-host", @@ -2269,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-host", @@ -2290,7 +2291,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-behavior", "craft-host", @@ -2309,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "base64 0.22.1", "chrono", @@ -2341,7 +2342,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "flate2", "serde", @@ -2352,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2362,7 +2363,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "js-sys", "serde_json", @@ -2373,7 +2374,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "winsafe", ] @@ -2381,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "craft-appkit", "craft-atomic", @@ -2413,7 +2414,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3772,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3781,7 +3782,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3799,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3817,12 +3818,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "flate2", "hayro-ccitt", @@ -4805,7 +4806,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4962,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index e1a20cac68..6cc18e4ea0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 30d529a5e7..aa3866728d 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index 09c57f22e4..636b8c81ef 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; use std::time::{Duration, Instant}; -use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SettingsStore, SharedSettings}; +use craft::settings::{LegacyFile, LoadReport, Location, OpenOptions, SectionError, SettingsStore, SharedSettings}; use vectorcraft_ui_egui::{AppSettings, from_app, parse_legacy}; use super::{VectorcraftApp, prefs_dir}; @@ -18,6 +18,15 @@ fn legacy_dir() -> Option<PathBuf> { prefs_dir::profile::prefs_dir(true) } +/// Parses the one `ui.json` slot of a legacy import: its bytes, or why it could not be read. +fn parse_legacy_slot(slots: &[Result<Option<&[u8]>, &std::io::Error>]) -> Result<(AppSettings, Vec<SectionError>), String> { + match slots.first() { + Some(Ok(Some(bytes))) => parse_legacy(bytes), + Some(Err(e)) => Err(e.to_string()), + _ => Err("the preferences file is missing".to_string()), + } +} + /// Where the log files live: `logs` in the preferences folder (see `logging`). pub(crate) fn log_dir() -> Option<PathBuf> { Some(prefs_dir::prefs_dir()?.join("logs")) @@ -34,7 +43,7 @@ pub(crate) fn prefs_enabled() -> bool { pub(crate) fn open_store() -> (SharedSettings<AppSettings>, LoadReport) { let (location, legacy) = match prefs_dir::prefs_dir().filter(|_| prefs_enabled()) { Some(dir) => { - let file = |dir: PathBuf| LegacyFile { path: dir.join(LEGACY_FILE), parse: parse_legacy }; + let file = |dir: PathBuf| LegacyFile { paths: vec![dir.join(LEGACY_FILE)], parse: parse_legacy_slot }; let legacy = std::iter::once(file(dir.clone())).chain(legacy_dir().map(file)).collect(); (Location::Dir(dir), legacy) } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 08f859b025..0cc8ea7d1c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,7 +5,7 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ - Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, + Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ShownBars, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; @@ -418,7 +418,7 @@ fn clear_of_scroll_bars(app: &VectorcraftApp, ui: &Ui, rect: egui::Rect) -> egui if app.ui.screen_mode >= 2 { return rect; } - CanvasScrollbars::clear_of(ui, rect, false, false) + CanvasScrollbars::clear_of(ui, rect, false, ShownBars::Both) } /// The scroll bars along the right and bottom edges (Normal and Full Screen with Menu Bar): the view diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index db83163e57..c4897d5c07 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -352,11 +352,11 @@ impl DocumentSettings for VcNewDocument { Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); - // The two buttons across the column, one above the other. + // The two buttons side by side, each as wide as its words. let (mut more, mut manage) = (None, None); - Stack::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { - more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").sizing(Sizing::FillWidth).show(ui)); - manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").sizing(Sizing::FillWidth).show(ui)); + Row::new().gap(Gap::Item).show(ui, |ui, _| { + more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").sizing(Sizing::Content).show(ui)); + manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").sizing(Sizing::Content).show(ui)); }); if let Some(more) = &more { let mut more_open = memory.more_open != clicked(more); @@ -1238,6 +1238,59 @@ mod tests { } } + /// The rows of Preset Details stand at least the framework's stack gap apart: the Height caption sits that far + /// below the Width field, and the Top bleed field that far below Height. Before, the rows were a tight gap apart + /// and each caption touched the field above it. + #[test] + fn preset_details_rows_stand_a_stack_gap_apart() { + use craft::ui::contract::Gap; + let mut stack = 0.0; + let mut theme = crate::testing::ui_context().run_ui(Default::default(), |ui| stack = Gap::Stack.points(ui)); + theme.textures_delta.clear(); + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let captions: Vec<(String, egui::Rect)> = crate::tests_labels::text_shapes(&out) + .into_iter() + .map(|(t, transform)| (t.galley.text().to_string(), transform * t.visual_bounding_rect())) + .collect(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let field = |label: &str| { + let (_, n) = nodes + .iter() + .find(|(_, n)| n.label() == Some(label) && n.role() == egui::accesskit::Role::SpinButton) + .unwrap_or_else(|| panic!("no field {label}")); + n.bounds().expect("bounds") + }; + let (width, height, top) = (field("Width"), field("Height"), field("Top")); + let caption_below = |text: &str, y: f64| { + captions.iter().filter(|(t, r)| t == text && f64::from(r.top()) >= y - 1.0).map(|(_, r)| f64::from(r.top())).fold(f64::INFINITY, f64::min) + }; + let height_caption = caption_below("Height", width.y1); + let gap = height_caption - width.y1; + assert!(gap + 0.5 >= f64::from(stack), "the Height caption stands {gap} below Width, at least the stack gap {stack}"); + let bleed_caption = caption_below("Bleed", height.y1); + assert!(bleed_caption < top.y0, "Bleed's caption {bleed_caption} stands above its Top field {top:?}"); + let gap = bleed_caption - height.y1; + assert!(gap + 0.5 >= f64::from(stack), "the Bleed caption stands {gap} below Height, at least the stack gap {stack}"); + } + + /// More Settings and Manage Profiles stand side by side, each as wide as its words, not across the whole column. + #[test] + fn more_settings_and_manage_profiles_stand_in_a_row() { + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: &str, role: egui::accesskit::Role| { + let (_, n) = nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} {label}")); + n.bounds().expect("bounds") + }; + let more = bounds("More Settings", egui::accesskit::Role::Button); + let manage = bounds("Manage Profiles", egui::accesskit::Role::Button); + assert!(more.x1 <= manage.x0 && (more.y0 - manage.y0).abs() < 1.0, "Manage Profiles {manage:?} follows More Settings {more:?} on its line"); + } + /// More Settings edits only the artboard layout, spacing and columns, and creates nothing. #[test] fn more_settings_is_a_popup_holding_only_the_artboard_layout() { @@ -1601,8 +1654,8 @@ mod tests { } } - /// In small windows Height and Artboards share a row, Orientation's two buttons stand side by side under them, and - /// the Bleed fields form two rows of two, Top and Bottom above Left and Right, with the link button after Right; + /// In small windows Height and Artboards share a row, Orientation's two buttons stand side by side, and the Bleed + /// fields stand in one row, or in two rows of two when the column is narrow, with the link button after Right; /// before, at 800 by 600 Orientation's buttons stood one above the other between Height and Artboards. #[test] fn new_document_details_stay_in_rows_in_small_windows() { @@ -1617,11 +1670,10 @@ mod tests { assert!(h.y0 == a.y0 && h.x1 <= a.x0, "{at}: Height {h:?} and Artboards {a:?} share a row"); assert!(a.y1 <= portrait.y0 || landscape.x1 <= a.x0, "{at}: Orientation {landscape:?} stays clear of Artboards {a:?}"); let [top, bottom, left, right] = ["Top", "Bottom", "Left", "Right"].map(|side| node(&nodes, side, Role::SpinButton)); - assert!(top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0, "{at}: two Bleed rows: {top:?} {bottom:?} {left:?} {right:?}"); - assert!( - top.x0 == left.x0 && bottom.x0 == right.x0 && top.x1 <= bottom.x0, - "{at}: two Bleed columns: {top:?} {bottom:?} {left:?} {right:?}" - ); + // A column wide enough holds the four fields in one row; a narrower one, in two rows of two. + let one_row = [bottom, left, right].iter().all(|f| f.y0 == top.y0) && top.x1 <= bottom.x0 && bottom.x1 <= left.x0 && left.x1 <= right.x0; + let two_rows = top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0 && top.x0 == left.x0 && bottom.x0 == right.x0; + assert!(one_row || two_rows, "{at}: the Bleed fields stand in one row or two: {top:?} {bottom:?} {left:?} {right:?}"); let link = node(&nodes, "Make all settings the same", Role::Button); assert!(right.x1 <= link.x0 && link.x1 <= dialog.x1, "{at}: the link button {link:?} follows Right {right:?} inside {dialog:?}"); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs index 8ddf49910a..5d2b67be4d 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -30,8 +30,9 @@ fn app() -> (VectorcraftApp, Vec<Value>, Value) { (app, reds, blue) } +/// The accessible name of a color's swatch: its tip, with the line break read as a space. fn label(hex: &str, n: u64) -> String { - format!("{hex}\n{}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) + format!("{hex} {}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) } fn has(p: &Panel, label: &str) -> bool { From 946774792acf80f8a97bb939d12d969cd885c9b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 30 Nov 2026 20:40:43 -0800 Subject: [PATCH 25/71] Pin craft-libs at 965c7beeb --- Cargo.lock | 172 ++++++++++++++++---------------- Cargo.toml | 76 +++++++------- apps/vectorcraft-web/Cargo.toml | 2 +- 3 files changed, 125 insertions(+), 125 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c831102d13..344ae8dc34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "accesskit", "craft-behavior", @@ -2220,7 +2220,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2231,7 +2231,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-host", @@ -2249,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-host", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-host", @@ -2291,7 +2291,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-behavior", "craft-host", @@ -2310,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "base64 0.22.1", "chrono", @@ -2342,7 +2342,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "flate2", "serde", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2363,7 +2363,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "js-sys", "serde_json", @@ -2374,7 +2374,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "winsafe", ] @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2414,7 +2414,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3773,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3782,7 +3782,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3800,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3818,12 +3818,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "flate2", "hayro-ccitt", @@ -4806,7 +4806,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4963,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=26f293d78494150f30b6d89d0375a62e54ef9927#26f293d78494150f30b6d89d0375a62e54ef9927" +source = "git+https://github.com/storytold/craft-libs?rev=965c7beeb6076480e016e448bddddcce0a738ff6#965c7beeb6076480e016e448bddddcce0a738ff6" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 6cc18e4ea0..fcc2a1ad8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index aa3866728d..824600f90a 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "26f293d78494150f30b6d89d0375a62e54ef9927", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "965c7beeb6076480e016e448bddddcce0a738ff6", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } From 0e480bfde0b96f015a68ff5dbd1c9466904daaf4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 30 Nov 2026 21:46:03 -0800 Subject: [PATCH 26/71] New document: pin the PDF check to the new craft-libs rev and require a Height caption xtask's pdf-deps check still named rev a5669ed2 after the workspace moved to 965c7bee, so it rejected the seven PDF packages. The layout test now fails when no Height caption stands below Width, instead of passing on an infinite gap. --- crates/ui-egui/src/dialogs/new_document.rs | 1 + xtask/src/pdf_deps.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index b3a4057a39..8e6ae908cd 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1277,6 +1277,7 @@ mod tests { captions.iter().filter(|(t, r)| t == text && f64::from(r.top()) >= y - 1.0).map(|(_, r)| f64::from(r.top())).fold(f64::INFINITY, f64::min) }; let height_caption = caption_below("Height", width.y1); + assert!(height_caption.is_finite(), "no Height caption stands below the Width field {width:?}"); let gap = height_caption - width.y1; assert!(gap + 0.5 >= f64::from(stack), "the Height caption stands {gap} below Width, at least the stack gap {stack}"); let bleed_caption = caption_below("Bleed", height.y1); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 216d23d43d..337ba6325e 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"; +const REV: &str = "965c7beeb6076480e016e448bddddcce0a738ff6"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 1dbbf874361974c88fe2770d2c1303b37a104e28 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 30 Nov 2026 21:56:24 -0800 Subject: [PATCH 27/71] Tests: guards check the environment, not the output under test Several tests returned early when the code under test gave back nothing, so the regression they guard against passed. Each of those guards now checks only what the host provides (an installed face, the bundled fonts), and the output itself is asserted: - PDF live text: the lam-alef face is no longer picked by whether its type imports (#6072); Insert Kashidas asserts the kashida and the imported type. - Effects and Expand Appearance on type assert the outlines and the drawn type when the default face is installed. - The OpenType panel's Stylistic Sets test asserts sets with the bundled fonts. - Thumbnail worker tests assert that the worker starts; the memory peak test asserts a reading. - The json2 test checks the interpreter's Date, replace and RegExp on every run, before looking for json2.js. - Devanagari arrow keys and the Arabic narrow-area wrap assert the layout they set up. --- apps/vectorcraft-cli/src/perf.rs | 3 +-- crates/effects/src/tests/rasterfollow.rs | 20 ++++++++++++++++---- crates/engine/src/tests/objexpand.rs | 6 ++++-- crates/js/tests/json2.rs | 14 +++++--------- crates/pdf/src/tests/live_text.rs | 6 +++--- crates/pdf/src/tests/realtext.rs | 18 +++++++----------- crates/text/src/layout/wrapping_tests.rs | 8 ++++---- crates/tools/src/text/tests.rs | 13 +------------ crates/ui-egui/src/panels/opentype.rs | 3 ++- crates/ui-egui/src/thumb_worker.rs | 4 ++-- 10 files changed, 45 insertions(+), 50 deletions(-) diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..ca0108f955 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -654,8 +654,7 @@ mod tests { let held = rss_mb(); drop(buffer); let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else { - eprintln!("no memory reading (Linux without `ps`): nothing to check"); - return; + panic!("rss_mb gave no memory reading"); }; assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}"); } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index db34010c22..d0e4939e8e 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { use vectorcraft_doc::text::{CharStyle, TextObject}; let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); - if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } + assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths"); let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); let b = baked(g); assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); @@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec<Effect>) -> Node { n } +/// Whether the face of the default character style is installed, so that type lays out glyphs. +/// When it is, `type_node`'s type must outline to paths. +fn fonts() -> bool { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { + return false; + } + assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family); + true +} + /// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square /// centered on its origin. fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) { @@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) { /// image and the instance are checked. #[test] fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { - let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + let fonts = fonts(); if !fonts { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); } @@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef /// listed before that effect, as the canvas draws it, rather than staying type under one shadow. #[test] fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { - if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } @@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() { n }; let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; - if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index ffa8e83f40..7ae627e546 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() { let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); - let before = render(&s); - if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { eprintln!("skipped: built without a font that draws the type"); return; } + let before = render(&s); + assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red"); // The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow. let red = (100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0); diff --git a/crates/js/tests/json2.rs b/crates/js/tests/json2.rs index af408a4fef..521040373e 100644 --- a/crates/js/tests/json2.rs +++ b/crates/js/tests/json2.rs @@ -68,20 +68,16 @@ problem; #[test] fn json2_polyfill_round_trips_with_the_built_in_json() { + let mut realm = Realm::new(); + match realm.run(NEEDS) { + Ok(JsValue::Bool(true)) => {} + other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"), + } let Some(path) = json2_file() else { println!("json2: SKIPPED (no json2.js; run cargo xtask test262)"); return; }; let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let mut realm = Realm::new(); - match realm.run(NEEDS) { - Ok(JsValue::Bool(true)) => {} - Ok(JsValue::Bool(false)) => { - println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)"); - return; - } - other => panic!("json2: the built-in check failed: {other:?}"), - } match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) { Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"), other => panic!("json2: {other:?}"), diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 90341ca28b..60a20079d6 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -503,13 +503,13 @@ fn arabic_ligatures_keep_their_letters_in_order() { let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style); vectorcraft_text::layout(db, &t).glyphs.len() == 1 }; - // An installed Arabic font with a lam-alef ligature whose glyphs come back as live type. + // An installed Arabic font with a lam-alef ligature. The test checks that its type comes + // back, so the choice of font does not depend on the import. let Some(face) = preferred .iter() .chain(&db.families()) .filter_map(|f| db.face(f, "Regular")) - .filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) - .find(|f| !imported_texts(f, "بب").is_empty()) + .find(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) else { return; // No such font on this host. }; diff --git a/crates/pdf/src/tests/realtext.rs b/crates/pdf/src/tests/realtext.rs index 7fcd06dd56..5f4ef0205f 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -202,8 +202,7 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva /// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either, /// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped -/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida, -/// or when PDF text import returns no strings on this platform. +/// without an OpenType font that covers Arabic and the tatweel. #[test] fn kashidas_are_not_written_as_hyphens() { let db = FontDb::global(); @@ -221,20 +220,17 @@ fn kashidas_are_not_written_as_hyphens() { t.para.justify = vectorcraft_doc::Justify::JustifyAll; t.para.kashida = vectorcraft_doc::text::Kashida::Medium; let tatweel = face.glyph_for('\u{0640}'); - if !vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel) { - return; - } + assert!( + vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel), + "{}: justified layout inserts a kashida", + face.family + ); let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text)); - if back.is_empty() { - return; - } + assert!(!back.is_empty(), "{}: the PDF's type comes back", face.family); assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}"); // Every letter comes back, at least as often as the text holds it (the justified words may // come back as type objects of their own). let all = back.concat(); - if all.is_empty() { - return; - } let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count(); for c in text.chars().filter(|c| c.is_alphabetic()) { assert!(count(&all, c) >= count(text, c), "{c}: {back:?}"); diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 225e58a053..5164dd1998 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -228,11 +228,10 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels); let mut shaped = Vec::new(); shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped); - let Some(first) = shaped.first() else { return }; + let first = shaped.first().expect("the text shapes to glyphs"); let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count(); - if first.byte != 0 || first_end < 2 || first_end >= shaped.len() { - return; - } + assert_eq!(first.byte, 0, "{}: the first cluster starts the text: {shaped:?}", face.family); + assert!(first_end >= 2 && first_end < shaped.len(), "{}: the base and its mark are one cluster of two glyphs: {shaped:?}", face.family); // Pick a narrow width that fits glyphs before one positive-advance glyph but not that next // glyph. This ensures the old per-glyph loop would have returned inside the first cluster. let mut prefix = shaped.first().map_or(0.0, |g| g.adv); @@ -245,6 +244,7 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { None } }); + // A face whose mark has no advance gives no width that splits the cluster. let Some(width) = width else { return }; let mut object = TextObject::point(Point::ZERO, text, style); diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index c6211550b3..ac4355e3a2 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -183,12 +183,7 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum(); assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance"); assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite"); - if split_width <= 0.0 { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}" - ); - return; - } + assert!(split_width > 0.0, "setup: {} lays out a positive-advance raw group at internal byte {split}", face.family); let width = prefix_width + split_width * 0.5; assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups"); @@ -205,12 +200,6 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6"); assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme"); assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end"); - if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}" - ); - return; - } assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred"); assert_eq!( (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start), diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 8715d02401..b2c8f2cbe2 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -855,7 +855,8 @@ mod tests { let mut app = selected_text(); let Some((st, _)) = text_style(&app) else { panic!("no text style") }; let sets = set_entries(&app, &st); - // Builds without the bundled fonts have no face that offers sets. + // With the bundled fonts, the text's face offers sets. Without them, an installed face may. + assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets"); let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index e9898a078f..5e7c48758c 100644 --- a/crates/ui-egui/src/thumb_worker.rs +++ b/crates/ui-egui/src/thumb_worker.rs @@ -214,7 +214,7 @@ mod tests { #[test] fn jobs_come_back_newest_last_per_slot() { - let Some(w) = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; for k in 1..=3 { assert!(w.submit(0, k, job(k))); @@ -238,7 +238,7 @@ mod tests { #[test] fn discarded_jobs_do_not_run_and_the_running_one_finishes() { - let Some(w) = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; // A job that holds the thread until it is let go, so the others queue behind it. let (started, running) = channel::<()>(); From bbf0e146ce48352d9725c5be2c13e270ed0b948c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 30 Nov 2026 22:10:15 -0800 Subject: [PATCH 28/71] New document: keep the overlap check for the two-row Bleed layout The two-row branch of the small-window test checked only where each column starts, so Top could reach into Bottom and Left into Right and still pass. --- crates/ui-egui/src/dialogs/new_document.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 8e6ae908cd..f70cb66b3c 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1684,6 +1684,7 @@ mod tests { // A column wide enough holds the four fields in one row; a narrower one, in two rows of two. let one_row = [bottom, left, right].iter().all(|f| f.y0 == top.y0) && top.x1 <= bottom.x0 && bottom.x1 <= left.x0 && left.x1 <= right.x0; let two_rows = top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0 && top.x0 == left.x0 && bottom.x0 == right.x0; + let two_rows = two_rows && top.x1 <= bottom.x0 && left.x1 <= right.x0; assert!(one_row || two_rows, "{at}: the Bleed fields stand in one row or two: {top:?} {bottom:?} {left:?} {right:?}"); let link = node(&nodes, "Make all settings the same", Role::Button); assert!(right.x1 <= link.x0 && link.x1 <= dialog.x1, "{at}: the link button {link:?} follows Right {right:?} inside {dialog:?}"); From 7407da03c8787b488d8d3b0ec5750a22e6fa1bd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 01:35:17 -0800 Subject: [PATCH 29/71] Tests: the Stylistic Sets submenu test reads the sets from the face The test reads the expected ss01 to ss20 sets from the text's face, compares them with the panel's entries and with the submenu's toggle rows in order, and checks that the submenu is left out when the face offers no sets. Before, a face whose sets the panel dropped returned early and skipped every submenu assertion. --- crates/ui-egui/src/panels/opentype.rs | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index b2c8f2cbe2..d61efcb289 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -857,6 +857,36 @@ mod tests { let sets = set_entries(&app, &st); // With the bundled fonts, the text's face offers sets. Without them, an installed face may. assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets"); + // The submenu lists the `ss01` to `ss20` sets that the text's face offers, read here from + // the face itself, so the test returns early only when the face offers none. + let db = FontDb::global(); + let available = db.has_family(&db.canonical(&st.font_family, &st.font_style).0); + let face_sets = if available { db.style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default() } else { Vec::new() }; + let expected: Vec<String> = face_sets.iter().filter(|set| (1..=20).contains(&set.number)).map(|set| format!("ss{:02}", set.number)).collect(); + let listed: Vec<String> = sets.iter().map(|(_, flag, _)| flag.tag().unwrap_or_default().to_string()).collect(); + assert_eq!(listed, expected, "the submenu lists the stylistic sets of the text's face"); + let rows = menu_rows(&app); + if expected.is_empty() { + assert!(!rows.iter().any(|row| matches!(row, PanelRow::Submenu(..))), "the submenu is left out when the face offers no sets"); + } else { + let submenu = rows.iter().find_map(|row| match row { + PanelRow::Submenu(_, sub) if (1..=20).any(|number| has_row(sub, &toggle_ref(&format!("ss{number:02}")))) => Some(sub), + _ => None, + }); + let actual: Vec<&str> = submenu + .expect("the menu has a Stylistic Sets submenu") + .iter() + .filter_map(|row| match row { + PanelRow::Command(c) if c.id == TOGGLE => Some(c.params["tag"].as_str().expect("a toggle has a tag")), + _ => None, + }) + .collect(); + assert_eq!(actual, expected, "the submenu toggle tags match the face's sets in order"); + } + for tag in &expected { + let r = toggle_ref(tag); + assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}"); + } let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); From ded4e473a29f73fe134197df041b26d95a5f0dfc Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 02:04:59 -0800 Subject: [PATCH 30/71] xtask: test-lint follows comments, inline and shared modules, and changed mod cfgs - never-run reads cfg predicates with comments removed, finds a module declared inside an inline module of its parent's parent, stops when several files declare a module with different attributes, and counts a change to a cfg on a mod declaration in another file against the tests it turns off. The lines between a module's cfg and the test no longer count as changes to the test. - reads-source ignores paths in comments. - census bounds weak_predicate at 64 levels and does not take a lookup with an operator before it as a round trip. - fixture-only treats a for-loop binding that shadows a fixture as unknown. - exact-pixel skips ratios and scaled values. - docs/development.md lists reads-source and never-run as failing rules. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 284 +++++++++++++++++++++++++++++++++++------ 2 files changed, 243 insertions(+), 43 deletions(-) diff --git a/docs/development.md b/docs/development.md index a1ceccaf59..7a6b8e04cf 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that no CI target builds because of a `cfg` on it or on a `mod` above it (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a5fc3e4bbc..bd00b6e833 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -240,6 +240,9 @@ pub struct Hit { /// only near `line`. pub first: usize, pub last: usize, + /// Other lines whose change counts as a change to the hit, by file: the `cfg` attributes that + /// turn a `never-run` test off, on its module or on a `mod` declaration in another file. + pub also: Vec<(String, usize, usize)>, } impl Hit { @@ -256,6 +259,18 @@ pub struct Ctx { pub helpers: HashMap<String, HashSet<String>>, pub ci_env: HashSet<String>, pub module_cfgs: HashMap<String, Vec<String>>, + /// Where the attributes of [`Ctx::module_cfgs`] are. + pub module_sites: HashMap<String, Vec<CfgSite>>, +} + +/// [`Ctx::module_cfgs`] and [`Ctx::module_sites`] for `paths`. +fn module_ctx(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> (HashMap<String, Vec<String>>, HashMap<String, Vec<CfgSite>>) { + let (mut cfgs, mut sites) = (HashMap::new(), HashMap::new()); + for (path, (preds, at)) in module_walk(paths, read) { + cfgs.insert(path.clone(), preds); + sites.insert(path, at); + } + (cfgs, sites) } /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. @@ -271,8 +286,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec<String> = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; + let (module_cfgs, module_sites) = module_ctx(&files, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs, module_sites }; let hits: Vec<Hit> = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); return Ok(()); @@ -283,18 +298,30 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let crates: BTreeSet<String> = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec<String> = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec<String> = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; + // Every file whose module a changed `mod` declaration governs is linted too, so a `cfg` added to + // `mod child;` counts against the tests in `child.rs`. + let cache: std::cell::RefCell<HashMap<String, Option<String>>> = Default::default(); + let read = |p: &str| cache.borrow_mut().entry(p.to_owned()).or_insert_with(|| read_small(root, p)).clone(); + let (module_cfgs, module_sites) = module_ctx(&files, &read); + let governed: Vec<String> = module_sites + .iter() + .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _)| changed.contains_key(decl))) + .map(|(p, _)| p.clone()) + .collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + if touches_in(&hit, &changed) { counted.push(hit); } else { older += 1; } } } + for (path, src) in read_all(root, &governed)? { + counted.extend(lint_file(&path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && touches_in(h, &changed))); + } finish(&counted, older, present.len(), &base) } @@ -544,7 +571,14 @@ fn hunk_range(hunk: &str) -> Option<(usize, usize)> { /// Whether `hit` covers a changed line (`None`: the whole file is new). fn touches(hit: &Hit, changed: Option<&BTreeSet<usize>>) -> bool { - changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) + let within = |lines: &BTreeSet<usize>, a: usize, b: usize| lines.range(a..=b).next().is_some(); + changed.is_none_or(|lines| within(lines, hit.first, hit.last) || hit.also.iter().any(|(p, a, b)| *p == hit.path && within(lines, *a, *b))) +} + +/// [`touches`] across files: the hit's own lines, or its [`Hit::also`] lines in any changed file. +fn touches_in(hit: &Hit, changed: &BTreeMap<String, Option<BTreeSet<usize>>>) -> bool { + let in_file = |p: &str, a: usize, b: usize| changed.get(p).is_some_and(|c| c.as_ref().is_none_or(|l| l.range(a..=b).next().is_some())); + changed.get(&hit.path).is_some_and(|c| touches(hit, c.as_ref())) || hit.also.iter().any(|(p, a, b)| in_file(p, *a, *b)) } // ---- What CI sets ---- @@ -1183,7 +1217,7 @@ struct File<'a> { impl File<'_> { fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { let line = self.lines.of(at); - Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, also: vec![] } } fn test_at(&self, pos: usize) -> &str { @@ -1586,12 +1620,21 @@ const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from /// Whether every operand of a (whitespace-free) condition or closure is a presence check alone. fn weak_predicate(pred: &str) -> bool { + weak_predicate_within(pred, 0) +} + +/// [`weak_predicate`] for at most 64 levels of nesting; deeper conditions are not judged, as in +/// [`census_condition`]. +fn weak_predicate_within(pred: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } let pred = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body); if pred.starts_with('(') && matching(pred.as_bytes(), 0) == Some(pred.len() - 1) { - return weak_predicate(&pred[1..pred.len() - 1]); + return weak_predicate_within(&pred[1..pred.len() - 1], depth + 1); } if let Some(at) = boolean_split(pred) { - return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); + return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); } let pred = pred.trim_start_matches('!'); if let Some(list) = pred.strip_suffix(".len()>0") { @@ -1636,6 +1679,8 @@ fn round_trip_call(op: &str) -> bool { op.match_indices(&format!("{r}(")).any(|(at, _)| { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) + // Only a path or receiver before the call: `offset + lookup(n)` is a derived value. + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '=', '!', ',', '&']) && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) }) }) @@ -2924,7 +2969,8 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let arg = norm(&file.src[open + 1..close]); + // Comments dropped, so `/* "src/lib.rs" */` beside a JSON path is not a hit. + let arg = file.src_norm((open + 1, close)); // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); @@ -3111,6 +3157,26 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(Strin } } } + // A nearer `for <pattern> in` binding of the name, whose block holds `before`, shadows the + // `let`: its value is unknown. + let found_at = match &found { + Some(Some((_, at))) => Some(*at), + _ => None, + }; + let shadows = |kw: &[u8], sep: &[u8]| { + words(body, kw, 0, before).into_iter().any(|at| { + let head = at + kw.len(); + let Some(open) = body[head..before].iter().position(|&c| c == b'{').map(|p| p + head) else { return false }; + let Some(split) = find(&body[..open], sep, head) else { return false }; + let pattern = &body[head..split]; + !words(pattern, name.as_bytes(), 0, pattern.len()).is_empty() + && matching(body, open).is_some_and(|close| open < before && before < close) + && found_at.is_none_or(|l| at > l) + }) + }; + if shadows(b"for", b" in ") { + return Some(None); + } found } @@ -3224,9 +3290,19 @@ fn cfg_value(p: &str, t: &Target) -> Option<bool> { } } +/// The text of a `cfg(…)` predicate without whitespace and comments; string literals keep their text. +fn cfg_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// The 1-based line of a byte offset. +fn line_at(b: &[u8], at: usize) -> usize { + b[..at.min(b.len())].iter().filter(|&&c| c == b'\n').count() + 1 +} + /// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with -/// the offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// the offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for at in words(m, b"cfg", 0, m.len()) { let before = m[..at].trim_ascii_end(); @@ -3255,76 +3331,133 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { }; if span.0 <= pos && pos <= span.1 { // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push((norm(&src[open + 1..close]), at)); + out.push((cfg_text(&src[open + 1..close]), at, end)); } } out } +/// A file that may declare a module, and the inline module it must be declared in, if any. +type Candidate = (String, Option<String>); +/// The predicates on a `mod` declaration and the first and last line of each attribute. +type Declared = (Vec<String>, Vec<(usize, usize)>); +/// A file that declares a module, whether it does so in an inline module, and what it declares. +type Owner = (String, bool, Declared); + /// The module name a file declares and the files that may declare it with `mod <name>;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples`). -fn module_parent(path: &str) -> Option<(&str, Vec<String>)> { +/// `examples`). A candidate that comes with a module name declares it inside that inline module +/// (`mod platform { mod child; }` in `src/lib.rs` for `src/platform/child.rs`); those come last. +fn module_parent(path: &str) -> Option<(&str, Vec<Candidate>)> { let (dir, file) = path.rsplit_once('/')?; let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; - let mut candidates: Vec<String> = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); - candidates.push(format!("{parent}.rs")); + let files_of = |dir: &str| -> Vec<String> { + let mut c: Vec<String> = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{dir}/{f}")).collect(); + c.push(format!("{dir}.rs")); + c + }; + let mut candidates: Vec<Candidate> = files_of(parent).into_iter().map(|c| (c, None)).collect(); + if let Some((grand, inline)) = parent.rsplit_once('/') { + candidates.extend(files_of(grand).into_iter().map(|c| (c, Some(inline.to_owned())))); + } Some((name, candidates)) } /// The predicates of the `#[cfg(…)]` attributes on a `mod <name>;` declaration in `src` and on the /// items and file around it, or `None` when `src` declares no such module. +#[cfg(test)] fn declared_cfgs(src: &str, name: &str) -> Option<Vec<String>> { + declared_cfg_spans(src, name, None).map(|(preds, _)| preds) +} + +/// [`declared_cfgs`] with the first and last line of each attribute. With `within`, only a +/// declaration inside the inline module of that name counts. +fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option<Declared> { let m = mask(src); - let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { + let named = |at: usize, word: &str, next: u8| { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') - })?; + (&m[start..end] == word.as_bytes() && m.get(skip_ws(&m, end)) == Some(&next)).then(|| skip_ws(&m, end)) + }; + let blocks: Option<Vec<(usize, usize)>> = within.map(|w| { + words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() + }); + let decl = words(&m, b"mod", 0, m.len()) + .into_iter() + .find(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c)))?; let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let mut out = vec![]; + let (mut preds, mut lines) = (vec![], vec![]); for at in words(&m, b"cfg", item, decl) { let open = skip_ws(&m, at + 3); let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { - out.push(norm(&src.as_bytes()[open + 1..close])); + preds.push(cfg_text(&src.as_bytes()[open + 1..close])); + lines.push((line_at(&m, at), line_at(&m, close))); } } - out.extend(cfgs_over(&m, src.as_bytes(), decl).into_iter().map(|(p, _)| p)); - Some(out) + for (p, at, end) in cfgs_over(&m, src.as_bytes(), decl) { + preds.push(p); + lines.push((line_at(&m, at), line_at(&m, end))); + } + Some((preds, lines)) } +/// Where a module's `cfg` attributes are: the declaring file and the attribute's first and last line. +pub type CfgSite = (String, usize, usize); + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the -/// modules above it, read through `read`. -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashMap<String, Vec<String>> { +/// modules above it, read through `read`, with where those attributes are. When several files +/// declare a module (`lib.rs` and `main.rs`) with different attributes, the walk stops there and +/// the module's ownership is unknown. +fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashMap<String, (Vec<String>, Vec<CfgSite>)> { let mut out = HashMap::new(); for path in paths { - let (mut preds, mut at) = (vec![], path.clone()); + let (mut preds, mut sites, mut at) = (vec![], vec![], path.clone()); for _ in 0..16 { let Some((name, candidates)) = module_parent(&at) else { break }; - let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { - break; + let found: Vec<Owner> = candidates + .into_iter() + .filter_map(|(c, within)| read(&c).and_then(|s| declared_cfg_spans(&s, name, within.as_deref())).map(|f| (c, within.is_some(), f))) + .collect(); + let direct = found.iter().any(|(_, inline, _)| !inline); + let owners: Vec<&Owner> = found.iter().filter(|(_, inline, _)| !inline || !direct).collect(); + let Some(first) = owners.first() else { break }; + let sorted = |p: &[String]| { + let mut p = p.to_vec(); + p.sort(); + p }; - preds.extend(found); - at = parent; + let base = sorted(&first.2.0); + if !owners.iter().all(|o| sorted(&o.2.0) == base) { + break; + } + preds.extend(first.2.0.iter().cloned()); + for o in &owners { + sites.extend(o.2.1.iter().map(|&(a, b)| (o.0.clone(), a, b))); + } + at = first.0.clone(); } if !preds.is_empty() { - out.insert(path.clone(), preds); + out.insert(path.clone(), (preds, sites)); } } out } +/// The predicates of [`module_walk`] alone. +#[cfg(test)] +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashMap<String, Vec<String>> { + module_walk(paths, read).into_iter().map(|(p, (preds, _))| (p, preds)).collect() +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option<Hit> { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); - // A change to an attribute that turns the test off counts as a change to the test. - let first_attr = local.iter().map(|&(_, at)| at).min(); - let mut preds: Vec<String> = local.into_iter().map(|(p, _)| p).collect(); + let mut preds: Vec<String> = local.iter().map(|(p, _, _)| p.clone()).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -3334,9 +3467,11 @@ fn never_run(v: &View, ctx: &Ctx) -> Option<Hit> { if CI_TARGETS.iter().chain(windows).all(off) { let shown: Vec<String> = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); - if let Some(at) = first_attr { - hit.first = hit.first.min(v.file.lines.of(at)); - } + // A change to an attribute that turns the test off counts as a change to the test; the + // lines between that attribute and the test do not. + let lines = &v.file.lines; + hit.also.extend(local.iter().map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); + hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().cloned()); return Some(hit); } None @@ -3366,6 +3501,10 @@ fn names_rect(op: &str) -> bool { if ["artboard", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { return false; } + // A ratio or a scaled value (`a.width() / b.width()`) is not a pixel size. + if op.trim_start_matches(['&', '*']).contains(['/', '*']) { + return false; + } let b = op.as_bytes(); let mut i = 0; while i < b.len() { @@ -3381,7 +3520,13 @@ fn names_rect(op: &str) -> bool { after = matching(b, after).map_or(b.len(), |c| c + 1); } let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` + // is a ratio, not a pixel size. + let ends = |r: &str| { + let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); + r.is_empty() || r.starts_with([',', ')', ']']) + }; + if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; } } @@ -3525,6 +3670,18 @@ mod tests { assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } + #[test] + fn census_skips_derived_lookups_and_deep_nesting() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); + let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(offset), [], "an operator before the lookup derives a value"); + let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(qualified), [(2, "census")]); + let deep = + format!("#[test]\nfn t() {{\n for c in COLORS {{\n assert!({}c.is_some(){});\n }}\n}}\n", "(".repeat(66), ")".repeat(66)); + assert_eq!(census(&deep), [], "nesting deeper than the limit is not judged"); + } + #[test] fn census_counts_rejections_and_helpers_as_checks() { let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); @@ -4954,7 +5111,7 @@ mod tests { let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; assert_eq!(only("mirror", ne), [], "two inputs that must differ"); let allowed = - "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; + "#[test]\nfn t() {\n // test-lint: allow mirror doubling is linear here\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; assert_eq!(only("mirror", allowed), []); } @@ -4967,6 +5124,8 @@ mod tests { assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let shadowed = "#[test]\nfn t() {\n let n = 1;\n for n in results() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "a loop binding that shadows the fixture"); let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; @@ -5050,8 +5209,46 @@ mod tests { let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; let found = lint_file("crates/x/src/tests.rs", src, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); - assert_eq!(hit, Some((1, 4))); - assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + assert_eq!(hit, Some((3, 4))); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", helper, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the cfg and the test"); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); + } + + #[test] + fn never_run_counts_a_changed_mod_declaration_in_another_file() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let ctx = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &ctx); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = |lines: &[usize]| BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))]); + assert!(touches_in(hit, &changed(&[1])), "the cfg on the declaration changed"); + assert!(!touches_in(hit, &changed(&[2])), "only the declaration line changed"); + } + + #[test] + fn never_run_resolves_inline_parents_and_several_owners() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(windows)]\nmod platform {\n mod child;\n}\n#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec<String> = ["crates/x/src/platform/child.rs", "crates/x/src/shared.rs"].into_iter().map(String::from).collect(); + let cfgs = module_cfgs(&paths, &read); + assert_eq!(cfgs.get("crates/x/src/platform/child.rs").map(Vec::as_slice), Some(&["windows".to_owned()][..])); + assert!(!cfgs.contains_key("crates/x/src/shared.rs"), "main.rs compiles it on every target"); } #[test] @@ -5063,6 +5260,7 @@ mod tests { assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); @@ -5079,5 +5277,7 @@ mod tests { assert_eq!(only("reads-source", read), [(3, "reads-source")]); let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", data), []); + let commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", commented), [], "a path in a comment"); } } From 6441c1b95be15cb4d4e899d8c059d12575af89c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 02:08:22 -0800 Subject: [PATCH 31/71] Tests: check exact values in panel and dialog tests Eleven assertions in the ui-egui Desaturate, Brush delete, Blend, Color Wheel, Color Balance, Remove Background and Document Info tests accepted halved, doubled or off-by-a-step values. Each now checks the value the test asks for. --- crates/ui-egui/src/addons/image/tests.rs | 3 +-- crates/ui-egui/src/dialogs/brush_delete/tests.rs | 3 ++- crates/ui-egui/src/dialogs/color_balance.rs | 4 ++-- crates/ui-egui/src/panels/doc_info.rs | 2 +- crates/ui-egui/src/panels/tests_blend.rs | 6 +++--- crates/ui-egui/src/panels/tests_color_wheel_hex.rs | 2 +- crates/ui-egui/src/panels/tests_color_wheel_opacity.rs | 4 ++-- crates/ui-egui/src/tests/plugins.rs | 6 ++++-- 8 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 154972dec7..3239ca6f00 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -248,6 +248,5 @@ fn properties_and_the_control_bar_remove_the_background_at_once() { assert!(closed(&app), "it runs at once"); assert_eq!(steps(&app), n + 1, "one undo step"); // The defaults (tolerance and softness 10): the white goes, the near-white ring fades. - let [corner, ring, block] = alphas(&app); - assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app)); + assert_eq!(alphas(&app), [0, 95, 255]); } diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index b712b589d9..402a2b1922 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -84,13 +84,14 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { let name = "10 pt. Oval"; app.run("brush.apply", json!({"name": name})).unwrap(); let before = app.session.active().unwrap().history.undo.len(); + let width = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap().width; ask(&mut app, json!({"name": name}), true); answer::<BrushDeleteQuestion>(&mut app, choice, pump); assert_eq!(open_question(&app), None); assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some())); let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name)); - assert!(stroke.width > 0.0); + assert_eq!(stroke.width, width, "the stroke keeps its width"); } } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 8c64b06a80..110c124717 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -437,8 +437,8 @@ mod tests { confirm(&mut app, &ctx); assert!(!app.session.in_interaction()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); - let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0]; - assert!(lighter > 0.6, "{lighter}"); + // #808080 holds less than 50% black, so taking 50% away leaves none. + assert_eq!(fill_hex(&app, id), "#ffffff"); } #[test] diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 5cb45f666a..13749667b9 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -950,7 +950,7 @@ mod tests { app.canvas.doc_info.clone().unwrap().1 }; let all = shown(&mut app, ""); - assert!(all["pathArea"].as_f64().is_some_and(|a| a > 0.0), "{}", all["pathArea"]); + assert!(all["pathArea"].as_f64().is_some_and(|a| (a - 200.0).abs() < 1e-6), "{}", all["pathArea"]); assert!(Arc::ptr_eq(&all, &shown(&mut app, "objects")), "Objects reuses All Categories' result"); for category in ["document", "fonts"] { let other = shown(&mut app, category); diff --git a/crates/ui-egui/src/panels/tests_blend.rs b/crates/ui-egui/src/panels/tests_blend.rs index 6aeaaeda67..1653488b5a 100644 --- a/crates/ui-egui/src/panels/tests_blend.rs +++ b/crates/ui-egui/src/panels/tests_blend.rs @@ -217,10 +217,10 @@ fn ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options() { assert_eq!(undo_depth(&p.app()), depth + 1, "one undo step for both blends"); // The value typed goes to both; each keeps its own spacing, type and the other value. if name == "Ramp:" { - assert!(after_a.ease.ramp > 0.0 && after_a.ease.ramp == after_b.ease.ramp, "{after_a:?} {after_b:?}"); + assert!((after_a.ease.ramp - 0.75).abs() < 1e-9 && (after_b.ease.ramp - 0.75).abs() < 1e-9, "{after_a:?} {after_b:?}"); assert_eq!((after_a.color_shift, after_b.color_shift), (before_a.color_shift, before_b.color_shift)); } else { - assert!(after_a.color_shift > 0.0 && after_a.color_shift == after_b.color_shift, "{after_a:?} {after_b:?}"); + assert_eq!((after_a.color_shift, after_b.color_shift), (75.0, 75.0), "{after_a:?} {after_b:?}"); assert_eq!((after_a.ease.ramp, after_b.ease.ramp), (before_a.ease.ramp, before_b.ease.ramp)); } assert_eq!((after_a.spacing, after_b.spacing), (BlendSpacing::Steps(3), BlendSpacing::Distance(12.0))); @@ -238,7 +238,7 @@ fn ramp_is_dimmed_while_a_selected_blend_has_no_spine() { assert!(!p.enabled("Ramp:") && p.enabled("Shift:")); p.type_into("Shift:", "75"); let app = p.app(); - assert!(spec(&app, a).color_shift > 0.0 && spec(&app, b).color_shift == spec(&app, a).color_shift); + assert_eq!((spec(&app, a).color_shift, spec(&app, b).color_shift), (75.0, 75.0)); } #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e2c5a62b80..5c1920d8c4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -452,7 +452,7 @@ fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { quick_click(&mut p, rail.rect.center()); let (hex, opacity) = first_stop(&p); assert_eq!(hex, "#336699", "the text applies"); - assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}"); + assert!((opacity - 0.5).abs() < 0.005, "the press sets the opacity: {opacity}"); } /// A press on the opacity slider that takes the focus from an edited field applies the text and diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 507b8280e2..f3b5ca6a47 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -94,7 +94,7 @@ fn the_row_shows_under_the_box_view() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); } /// A value this build does not read keeps the rest of the preferences and reads as the default. @@ -122,7 +122,7 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); let labels = undo_labels(&p.app()); assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000"); diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 6dc9853a2a..351efaec28 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -215,8 +215,10 @@ fn filter_dialog_previews_and_commits_one_undo_step() { set_field(&mut h, "amount", json!(50)).unwrap(); step(&mut h); assert!(h.state().session.in_interaction(), "previewing"); - let [r, g, _] = fill_rgb(h.state(), id); - assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}"); + let [r, g, b] = fill_rgb(h.state(), id); + for (got, want) in [(r, 0.6063), (g, 0.1063), (b, 0.1063)] { + assert!((got - want).abs() < 1e-4, "half desaturated on the canvas: {r} {g} {b}"); + } step(&mut h); let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame"); let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated(); From edcad3c1832ab0eec35b5ea94d3195492c14f501 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 02:39:39 -0800 Subject: [PATCH 32/71] Tests: test-lint judges negations, cfg escapes and module declarations exactly - census keeps the polarity of a negation: `!parse(x).is_ok()` is a rejection, while `!xs.is_empty()` stays a presence check. - reads-source looks at the last path literal of a read_to_string argument, so `root.join("fixtures.rs").join("input.json")` is not a hit. - never-run reads an escaped cfg string value as unknown, takes every `mod` declaration of a module (`#[cfg(windows)]` and `#[cfg(unix)]` both count), and ties a change to an attribute only when that attribute excludes a CI target. - exact-pixel does not count a coordinate passed to a function. - docs/development.md says when never-run can decide a cfg. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 173 ++++++++++++++++++++++++++++++++++------- 2 files changed, 147 insertions(+), 28 deletions(-) diff --git a/docs/development.md b/docs/development.md index 7a6b8e04cf..4244e28738 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that no CI target builds because of a `cfg` on it or on a `mod` above it (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index bd00b6e833..57b9cd41d0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -305,7 +305,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let (module_cfgs, module_sites) = module_ctx(&files, &read); let governed: Vec<String> = module_sites .iter() - .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _)| changed.contains_key(decl))) + .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _, _)| changed.contains_key(decl))) .map(|(p, _)| p.clone()) .collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; @@ -1636,7 +1636,12 @@ fn weak_predicate_within(pred: &str, depth: usize) -> bool { if let Some(at) = boolean_split(pred) { return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); } - let pred = pred.trim_start_matches('!'); + let bare = pred.trim_start_matches('!'); + if (pred.len() - bare.len()) % 2 == 1 { + // A negated check is a presence check only for `!xs.is_empty()`; `!parse(x).is_ok()` asserts a rejection. + return bare.ends_with(".is_empty()") && !bare.contains(['=', '<', '>']); + } + let pred = bare; if let Some(list) = pred.strip_suffix(".len()>0") { return !list.contains(['=', '<', '>']); } @@ -2954,6 +2959,13 @@ fn sleep_hits(file: &File) -> Vec<Hit> { .collect() } +/// The contents of the last string literal in `s`, without its quotes. +fn last_literal(s: &str) -> Option<&str> { + let close = s.rfind('"')?; + let open = s[..close].rfind('"')?; + Some(&s[open + 1..close]) +} + fn reads_source_hits(file: &File) -> Vec<Hit> { if SOURCE_AUDITS.contains(&file.path) { return vec![]; @@ -2976,8 +2988,9 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { let literal = raw.unwrap_or(&arg); let rs = match word { b"ends_with" => literal == "\".rs\"", - // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. - b"read_to_string" => arg.contains(".rs\""), + // The last path literal in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`, but not + // `root.join("fixtures.rs").join("input.json")`. + b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3278,6 +3291,10 @@ fn cfg_value(p: &str, t: &Target) -> Option<bool> { } // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + // An escape in an ordinary string (`"lin\x75x"`) is not decoded, so its value is unknown. + if p.split_once('=').is_some_and(|(_, v)| !v.starts_with('r') && v.contains('\\')) { + return None; + } match key { "test" => Some(true), "unix" => Some(t.family == "unix"), @@ -3339,8 +3356,9 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { /// A file that may declare a module, and the inline module it must be declared in, if any. type Candidate = (String, Option<String>); -/// The predicates on a `mod` declaration and the first and last line of each attribute. -type Declared = (Vec<String>, Vec<(usize, usize)>); +/// The predicates on a `mod` declaration and the first and last line of each attribute, with the +/// predicate that attribute contributes. +type Declared = (Vec<String>, Vec<(usize, usize, String)>); /// A file that declares a module, whether it does so in an inline module, and what it declares. type Owner = (String, bool, Declared); @@ -3386,28 +3404,54 @@ fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option<Dec let blocks: Option<Vec<(usize, usize)>> = within.map(|w| { words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() }); - let decl = words(&m, b"mod", 0, m.len()) + let decls: Vec<usize> = words(&m, b"mod", 0, m.len()) .into_iter() - .find(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c)))?; - let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let (mut preds, mut lines) = (vec![], vec![]); - for at in words(&m, b"cfg", item, decl) { - let open = skip_ws(&m, at + 3); - let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); - if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { - preds.push(cfg_text(&src.as_bytes()[open + 1..close])); - lines.push((line_at(&m, at), line_at(&m, close))); - } + .filter(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c))) + .collect(); + let mut each = decls.iter().map(|&decl| decl_cfg_spans(&m, src, decl)); + let first = each.next()?; + let rest: Vec<Declared> = each.collect(); + if rest.iter().all(|(p, _)| *p == first.0) { + let mut lines = first.1; + lines.extend(rest.into_iter().flat_map(|(_, l)| l)); + return Some((first.0, lines)); } - for (p, at, end) in cfgs_over(&m, src.as_bytes(), decl) { - preds.push(p); - lines.push((line_at(&m, at), line_at(&m, end))); + // Declarations under different `cfg`s (`#[cfg(windows)] mod child;` and `#[cfg(unix)] mod child;`): + // the module is compiled where any of them holds. + let (mut alts, mut spans) = (vec![], vec![]); + for (p, l) in std::iter::once(first).chain(rest) { + alts.push(format!("all({})", p.join(","))); + spans.extend(l.into_iter().map(|(a, b, _)| (a, b))); } - Some((preds, lines)) + let any = format!("any({})", alts.join(",")); + let lines = spans.into_iter().map(|(a, b)| (a, b, any.clone())).collect(); + Some((vec![any], lines)) } -/// Where a module's `cfg` attributes are: the declaring file and the attribute's first and last line. -pub type CfgSite = (String, usize, usize); +/// The predicates of the `#[cfg(…)]` attributes on the `mod` declaration at `decl` of masked `m` +/// and on the items and file around it, with the first and last line of each attribute. +fn decl_cfg_spans(m: &[u8], src: &str, decl: usize) -> Declared { + let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let (mut preds, mut lines) = (vec![], vec![]); + for at in words(m, b"cfg", item, decl) { + let open = skip_ws(m, at + 3); + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() { + let p = cfg_text(&src.as_bytes()[open + 1..close]); + lines.push((line_at(m, at), line_at(m, close), p.clone())); + preds.push(p); + } + } + for (p, at, end) in cfgs_over(m, src.as_bytes(), decl) { + lines.push((line_at(m, at), line_at(m, end), p.clone())); + preds.push(p); + } + (preds, lines) +} + +/// Where a module's `cfg` attributes are: the declaring file, the attribute's first and last line, +/// and its predicate. +pub type CfgSite = (String, usize, usize, String); /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`, with where those attributes are. When several files @@ -3437,7 +3481,7 @@ fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashM } preds.extend(first.2.0.iter().cloned()); for o in &owners { - sites.extend(o.2.1.iter().map(|&(a, b)| (o.0.clone(), a, b))); + sites.extend(o.2.1.iter().map(|(a, b, p)| (o.0.clone(), *a, *b, p.clone()))); } at = first.0.clone(); } @@ -3470,8 +3514,11 @@ fn never_run(v: &View, ctx: &Ctx) -> Option<Hit> { // A change to an attribute that turns the test off counts as a change to the test; the // lines between that attribute and the test do not. let lines = &v.file.lines; - hit.also.extend(local.iter().map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); - hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().cloned()); + // An attribute whose predicate holds on every target CI tests on (`unix` without Windows) + // does not turn the test off. + let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true)); + hit.also.extend(local.iter().filter(|(p, _, _)| excludes(p)).map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); + hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().filter(|s| excludes(&s.3)).map(|(f, a, b, _)| (f.clone(), *a, *b))); return Some(hit); } None @@ -3522,9 +3569,10 @@ fn names_rect(op: &str) -> bool { let rest = &op[after..]; // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` // is a ratio, not a pixel size. + // A `)` must close a tuple group: in `column_for_x(rect.min.x)` it closes a call's arguments. let ends = |r: &str| { let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); - r.is_empty() || r.starts_with([',', ')', ']']) + r.is_empty() || r.starts_with([',', ']']) || (r.starts_with(')') && !closes_call(b, op.len() - r.len())) }; if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; @@ -3535,6 +3583,22 @@ fn names_rect(op: &str) -> bool { false } +/// Whether the `)` at `close` ends the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) rather +/// than a tuple or a parenthesized group. +fn closes_call(b: &[u8], close: usize) -> bool { + let mut depth = 0i32; + for i in (0..close).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth > 0 => depth -= 1, + b'(' => return i > 0 && (is_ident(b[i - 1]) || b[i - 1] == b'!' || b[i - 1] == b'>'), + b'[' | b'{' => return false, + _ => {} + } + } + false +} + /// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders. fn only_numbers(op: &str) -> bool { let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", ""); @@ -5267,6 +5331,8 @@ mod tests { assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test"); assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed on"); + assert_eq!(px("assert_eq!((button_rect.min.x, button_rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } @@ -5279,5 +5345,58 @@ mod tests { assert_eq!(only("reads-source", data), []); let commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", commented), [], "a path in a comment"); + let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", dir), [], "a directory whose name ends in .rs"); + } + + #[test] + fn weak_predicates_keep_the_polarity_of_a_negation() { + assert!(weak_predicate("parse(input).is_ok()")); + assert!(weak_predicate("!xs.is_empty()")); + assert!(!weak_predicate("!parse(input).is_ok()"), "a rejection"); + assert!(!weak_predicate("!x.is_some()"), "an absence"); + assert!(weak_predicate("!!x.is_some()")); + } + + #[test] + fn never_run_reads_escaped_values_as_unknown() { + let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", escaped), []); + } + + #[test] + fn never_run_takes_every_declaration_of_a_module() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let both = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/child.rs", test, &both), [], "the unix declaration builds it on Linux"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let windows = Ctx { module_cfgs, module_sites, ..ctx() }; + assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]); + } + + #[test] + fn never_run_does_not_count_a_cfg_true_on_every_target() { + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(unix)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let unix = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &unix); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some([1].into_iter().collect()))]); + assert!(!touches_in(hit, &changed), "cfg(unix) holds on Linux and FreeBSD"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let mac = Ctx { module_cfgs, module_sites, ..ctx() }; + let found = lint_file("crates/x/src/child.rs", test, &mac); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches_in(hit, &changed), "a macOS-only module cfg"); } } From 0b41498af652c2dc6a42eccfb67fe4f595f73abe Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 03:06:35 -0800 Subject: [PATCH 33/71] Tests: test-lint reads format paths, nested mod declarations and call arguments exactly - reads-source checks the format string of a format!(...) path, so a format argument ending in .rs is not taken for the file name. - never-run combines only the mod declarations that load the same file; a declaration inside another inline module loads a file under that module's directory. - exact-pixel treats a comma inside a call's arguments like the closing parenthesis, so f(rect.min.x, 3) is a coordinate passed on. --- xtask/src/test_lint.rs | 57 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 57b9cd41d0..55b90d8b4a 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2966,6 +2966,16 @@ fn last_literal(s: &str) -> Option<&str> { Some(&s[open + 1..close]) } +/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call, since +/// its arguments fill placeholders inside it, otherwise the last string literal. +fn path_literal(arg: &str) -> Option<&str> { + let Some(at) = arg.find("format!(") else { return last_literal(arg) }; + let rest = &arg[at + "format!(".len()..]; + let open = rest.find('"')?; + let close = rest[open + 1..].find('"')? + open + 1; + Some(&rest[open + 1..close]) +} + fn reads_source_hits(file: &File) -> Vec<Hit> { if SOURCE_AUDITS.contains(&file.path) { return vec![]; @@ -2989,8 +2999,8 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { let rs = match word { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`, but not - // `root.join("fixtures.rs").join("input.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs")), + // `root.join("fixtures.rs").join("input.json")` or `format!("{}/input.json", "fixtures.rs")`. + b"read_to_string" => path_literal(&arg).is_some_and(|l| l.ends_with(".rs")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3404,9 +3414,29 @@ fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option<Dec let blocks: Option<Vec<(usize, usize)>> = within.map(|w| { words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() }); + // Every inline `mod <any> { … }`: a declaration counts only when its innermost enclosing inline + // module is the one `within` names (or, without `within`, when it has none), since a declaration + // nested deeper loads a file under that other module's directory. + let inline: Vec<(usize, usize)> = words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + let o = skip_ws(&m, end); + (end > start && m.get(o) == Some(&b'{')).then(|| matching(&m, o).map(|c| (o, c))).flatten() + }) + .collect(); + let innermost = |at: usize| inline.iter().filter(|&&(o, c)| o < at && at < c).max_by_key(|&&(o, _)| o).copied(); let decls: Vec<usize> = words(&m, b"mod", 0, m.len()) .into_iter() - .filter(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c))) + .filter(|&at| { + named(at, name, b';').is_some() + && match (&blocks, innermost(at)) { + (None, inner) => inner.is_none(), + (Some(bs), Some(inner)) => bs.contains(&inner), + (Some(_), None) => false, + } + }) .collect(); let mut each = decls.iter().map(|&decl| decl_cfg_spans(&m, src, decl)); let first = each.next()?; @@ -3569,10 +3599,11 @@ fn names_rect(op: &str) -> bool { let rest = &op[after..]; // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` // is a ratio, not a pixel size. - // A `)` must close a tuple group: in `column_for_x(rect.min.x)` it closes a call's arguments. + // A `)` or `,` must belong to a tuple group: in `column_for_x(rect.min.x)` and + // `f(rect.min.x, 2)` it is part of a call's arguments. let ends = |r: &str| { let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); - r.is_empty() || r.starts_with([',', ']']) || (r.starts_with(')') && !closes_call(b, op.len() - r.len())) + r.is_empty() || r.starts_with(']') || (r.starts_with([')', ',']) && !closes_call(b, op.len() - r.len())) }; if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; @@ -3583,8 +3614,8 @@ fn names_rect(op: &str) -> bool { false } -/// Whether the `)` at `close` ends the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) rather -/// than a tuple or a parenthesized group. +/// Whether the `)` or `,` at `close` is in the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) +/// rather than in a tuple or a parenthesized group. fn closes_call(b: &[u8], close: usize) -> bool { let mut depth = 0i32; for i in (0..close).rev() { @@ -5264,7 +5295,11 @@ mod tests { let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; - assert_eq!(declared_cfgs(block, "child"), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfg_spans(block, "child", Some("platform")).map(|(p, _)| p), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfgs(block, "child"), None, "the nested declaration loads platform/child.rs"); + let nested = "#[cfg(windows)]\nmod child;\nmod other {\n mod child;\n}\n"; + assert_eq!(declared_cfgs(nested, "child"), Some(vec!["windows".to_owned()]), "other/child.rs is another file"); + assert_eq!(declared_cfg_spans(nested, "child", Some("other")).map(|(p, _)| p), Some(vec![])); assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); } @@ -5332,6 +5367,7 @@ mod tests { assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed on"); + assert_eq!(px("assert_eq!(cell_at(button_rect.min.x, 3), 2);"), [], "a coordinate passed on before another argument"); assert_eq!(px("assert_eq!((button_rect.min.x, button_rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); @@ -5347,6 +5383,11 @@ mod tests { assert_eq!(only("reads-source", commented), [], "a path in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory whose name ends in .rs"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/input.json\", \"fixtures.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument that ends in .rs"); + let formatted_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted_rs), [(3, "reads-source")]); } #[test] From cefd2ed69ebc1c66fcbdc5e1b27249826a9943e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 03:32:16 -0800 Subject: [PATCH 34/71] Tests: test-lint reads the path a join adds after a format call read_to_string(PathBuf::from(format!("{}/fixtures.rs", root)).join("input.json")) was reported as reading Rust source, and a join of "lib.rs" after a format call was missed. path_literal now takes a literal after the format call's closing parenthesis as the end of the path. --- xtask/src/test_lint.rs | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 55b90d8b4a..ebde101afe 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2966,14 +2966,39 @@ fn last_literal(s: &str) -> Option<&str> { Some(&s[open + 1..close]) } -/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call, since -/// its arguments fill placeholders inside it, otherwise the last string literal. +/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call that ends the path, since +/// its arguments fill placeholders inside it, otherwise the last string literal. A literal after the `format!(…)` +/// call (`PathBuf::from(format!(…)).join("lib.rs")`) ends the path instead. fn path_literal(arg: &str) -> Option<&str> { let Some(at) = arg.find("format!(") else { return last_literal(arg) }; let rest = &arg[at + "format!(".len()..]; - let open = rest.find('"')?; - let close = rest[open + 1..].find('"')? + open + 1; - Some(&rest[open + 1..close]) + let b = rest.as_bytes(); + let (mut depth, mut i, mut end) = (0usize, 0, None); + while i < b.len() { + match b[i] { + b'"' => { + i += 1; + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + } + b'(' => depth += 1, + b')' if depth == 0 => { + end = Some(i); + break; + } + b')' => depth -= 1, + _ => {} + } + i += 1; + } + let call = &rest[..end.unwrap_or(rest.len())]; + if let Some(tail) = end.map(|e| &rest[e + 1..]).filter(|t| t.contains('"')) { + return path_literal(tail); + } + let open = call.find('"')?; + let close = call[open + 1..].find('"')? + open + 1; + Some(&call[open + 1..close]) } fn reads_source_hits(file: &File) -> Vec<Hit> { @@ -5388,6 +5413,10 @@ mod tests { let formatted_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted_rs), [(3, "reads-source")]); + let joined_json = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures.rs\", root)).join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined_json), [], "a join after the format call ends the path"); + let joined_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures\", root)).join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined_rs), [(3, "reads-source")]); } #[test] From 408661218f87a3d95542151a727f146ec1fc99a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 04:05:40 -0800 Subject: [PATCH 35/71] Test lint: reads-source spans the path; cfg search skips later attributes A reads-source hit now runs through the call's closing parenthesis, so changing a path on a later line of a multiline call counts as a change to the hit. The never-run cfg search skips whole attributes after the cfg, so a `;` inside `#[test_case(1; "one")]` no longer drops the cfg. --- xtask/src/test_lint.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index ebde101afe..4cc143a2d0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -235,7 +235,7 @@ pub struct Hit { /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's - /// `]` for `ignore-without-reason`, else `line`. This span + /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. pub first: usize, @@ -3029,7 +3029,10 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { - out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + // Through the call's `)`, so a change to a path on a later line is a change to the hit. + let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into()); + hit.last = file.lines.of(close); + out.push(hit); } } } @@ -3374,7 +3377,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let enclosing = m[..at].iter().rposition(|&c| c == b'{'); enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) } else { - let after = end + 1; + // Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole, as `fn_after` does. + let mut after = end + 1; + while m[skip_ws(m, after)..].starts_with(b"#[") { + let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; + after = close + 1; + } let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; match (m[open], matching(m, open)) { (b'{', Some(close)) => (at, close), @@ -5289,6 +5297,16 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", other), [], "a cfg on another item"); + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); + } + + #[test] + fn reads_source_spans_reach_a_path_on_a_later_line() { + let src = "#[test]\nfn t() {\n let s = fs::read_to_string(\n root.join(\"src/lib.rs\"),\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + let found: Vec<Hit> = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::ReadsSource).collect(); + assert_eq!(found.iter().map(|h| (h.line, h.first, h.last)).collect::<Vec<_>>(), [(3, 3, 5)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the path alone"); } #[test] From c52314a75a9554e0de1ac4fdaca3f7d3c5593c55 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 04:11:45 -0800 Subject: [PATCH 36/71] Library panels: build browser rows once per library, not every frame A library panel rebuilt every browser row, with its tooltip and name index, on each frame, and the browser's memo key hashed every row each frame. With a swatch library of thousands of swatches, scrolling the thumbnail grid spent most of each frame on that work. The panel now keeps the rows it built for the library contents it shows and the UI language, and builds them again only when either changes. The memo key names that build instead of hashing the rows. Rows of panels that have closed are dropped when rows are next built. Pattern sources no longer copy every swatch name to find the few patterns. --- crates/ui-egui/src/panels/brushes.rs | 3 + crates/ui-egui/src/panels/graphic_styles.rs | 3 + crates/ui-egui/src/panels/library_panel.rs | 88 +++++++++++++++---- .../ui-egui/src/panels/library_panel/tests.rs | 24 +++++ .../ui-egui/src/panels/swatches/libraries.rs | 5 +- crates/ui-egui/src/panels/symbols.rs | 4 + 6 files changed, 109 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index d8075d4c66..aaccca637b 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -884,6 +884,9 @@ impl LibraryKind for BrushLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option<String> { app.session.brush_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Rc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibBrush>> { lib.iter().map(|b| Row { name: b.name(), item: Some(b) }).collect() } diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d9250ad7ee..e6668323a8 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1004,6 +1004,9 @@ impl LibraryKind for GraphicStyleLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option<String> { app.session.style_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibStyle>> { lib.iter().map(|s| Row { name: &s.style().name, item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..529671ccce 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -15,9 +15,11 @@ //! Library… (`ui.libraryPanel.locate`). The find text is the browser's; the selection is panel state //! (`UiState::library_selection`). +use std::any::Any; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; +use std::rc::Rc; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; @@ -25,9 +27,7 @@ use craft::theme::variant::Tone; use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::{Notice, NoticeAction, NoticeLayout}; -use craft::ui::patterns::presets::{ - PresetBrowser, PresetEvent, PresetFns, PresetKind, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView, -}; +use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView}; use craft::ui::primitives::{ContentPainterCx, IconSpec}; use craft::ui::runtime::access::PopupKind; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; @@ -122,7 +122,7 @@ pub(crate) trait LibraryKind { /// The view a panel shows until another is picked. const VIEW: View = View::MediumThumb; /// A library's contents, cheap to clone. - type Lib; + type Lib: Clone + 'static; type Item: Sync; /// What the thumbnails paint with besides each item (a panel setting, the documents a library's patterns come /// from); `()` for nothing. @@ -135,6 +135,9 @@ pub(crate) trait LibraryKind { fn find(app: &VectorcraftApp, key: &str) -> Found; /// The file library `id` was read from, if any. fn path(app: &VectorcraftApp, id: &str) -> Option<String>; + /// Whether `a` and `b` are the same contents, not only equal ones: the panel reuses the browser rows it built for + /// `a` while [`get`](Self::get) returns `b`. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool; /// The rows of library `id`; the browser's search filters what it shows (by the shown name and /// [`PresetRow::search_name`]). fn rows<'a>(lib: &'a Self::Lib, id: &str) -> Vec<Row<'a, Self::Item>>; @@ -608,6 +611,7 @@ fn saved_view(view: PresetView, zoom: f64) -> View { /// The browser rows of library `id`'s `rows`, flat: a folder is a row of its own before its items, which a click /// selects as it selects an item (production's folder tiles neither opened nor closed). fn browser_rows<K: LibraryKind>(panel: &str, id: &str, rows: &[Row<K::Item>]) -> Vec<PresetRow<LibraryKey>> { + BUILDS.with(|n| n.set(n.get() + 1)); rows.iter() .map(|r| { let label = K::label(id, r.name); @@ -624,22 +628,73 @@ fn browser_rows<K: LibraryKind>(panel: &str, id: &str, rows: &[Row<K::Item>]) -> .collect() } +/// A library panel's browser rows, built for one library's contents in one UI language. +struct BuiltRows<L> { + /// The contents the rows were built from, held so that [`LibraryKind::same`] does not match other contents + /// later stored at the same address. + lib: L, + lang: crate::i18n::Lang, + /// Different for every build, so the browser's memo key changes with the rows. + build: u64, + rows: Rc<Vec<PresetRow<LibraryKey>>>, + /// Each item row's position in [`LibraryKind::rows`], by stored name. + items: Rc<HashMap<String, usize>>, +} + +thread_local! { + /// Each library panel's [`BuiltRows`], by panel id. + static BUILT_ROWS: RefCell<HashMap<String, Box<dyn Any>>> = RefCell::new(HashMap::new()); + /// How many times [`browser_rows`] has run, for tests. + static BUILDS: Cell<u64> = const { Cell::new(0) }; +} + +/// How many times the panels have built browser rows on this thread. +#[cfg(test)] +pub(crate) fn row_builds() -> u64 { + BUILDS.with(Cell::get) +} + +/// [`BuiltRows::build`], [`BuiltRows::rows`] and [`BuiltRows::items`]. +type Built = (u64, Rc<Vec<PresetRow<LibraryKey>>>, Rc<HashMap<String, usize>>); + +/// Panel `panel`'s browser rows of `lib`: the ones built before while the panel shows the same contents in the same +/// language, otherwise built now. Building drops the rows of the panels that are no longer open in `ui`. +fn built_rows<K: LibraryKind>(ui: &UiState, panel: &str, id: &str, lib: &K::Lib) -> Built { + let lang = crate::i18n::current(); + BUILT_ROWS.with(|cache| { + let mut cache = cache.borrow_mut(); + if let Some(b) = cache.get(panel).and_then(|b| b.downcast_ref::<BuiltRows<K::Lib>>()) + && b.lang == lang + && K::same(&b.lib, lib) + { + return (b.build, b.rows.clone(), b.items.clone()); + } + let flat = K::rows(lib, id); + let rows = Rc::new(browser_rows::<K>(panel, id, &flat)); + let items = Rc::new(flat.iter().enumerate().filter(|(_, r)| r.item.is_some()).map(|(i, r)| (r.name.to_string(), i)).collect()); + let build = BUILDS.with(Cell::get); + let built = BuiltRows { lib: lib.clone(), lang, build, rows: rows.clone(), items: Rc::clone(&items) }; + cache.retain(|p, _| is_open(ui, p)); + cache.insert(panel.to_string(), Box::new(built)); + (build, rows, items) + }) +} + /// What a library's browser shows: its rows, the items their thumbnails paint and what those paint with. struct Shown<'a, K: LibraryKind> { + /// [`BuiltRows::build`] of `rows`. + build: u64, rows: &'a [PresetRow<LibraryKey>], - items: HashMap<&'a str, &'a K::Item>, + flat: &'a [Row<'a, K::Item>], + items: &'a HashMap<String, usize>, thumbs: K::Thumbs, } -/// By the rows (each names its library and item, whose look a library keeps) and what the thumbnails paint with. +/// By the build of the rows (each names its library and item, whose look a library keeps) and what the thumbnails +/// paint with. impl<K: LibraryKind> MemoProps for Shown<'_, K> { fn key(&self, key: &mut MemoKey) { - for row in self.rows { - row.key.key(key); - row.label.key(key); - row.depth.key(key); - (row.kind == PresetKind::Item).key(key); - } + self.build.key(key); self.rows.len().key(key); self.thumbs.key(key); } @@ -658,15 +713,14 @@ fn body<K: LibraryKind>(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { }; let panel = panel_id(K::KIND, id); let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find)); + let (build, rows, items) = built_rows::<K>(&app.ui, &panel, id, &lib); let flat = K::rows(&lib, id); - let rows = browser_rows::<K>(&panel, id, &flat); - let items = flat.iter().filter_map(|r| r.item.map(|i| (r.name, i))).collect(); let fns = PresetFns::new(|shown: &Shown<'_, K>, _| shown.rows.to_vec()).thumb(|shown, cx, rect, info| { - if let Some(item) = shown.items.get(info.key.name.as_str()) { + if let Some(item) = shown.items.get(info.key.name.as_str()).and_then(|&i| shown.flat.get(i)).and_then(|r| r.item) { K::thumb(&shown.thumbs, cx, rect, item); } }); - let source = PresetSource::new(Shown::<K> { rows: &rows, items, thumbs: K::thumbs(app, &lib) }, fns); + let source = PresetSource::new(Shown::<K> { build, rows: &rows, flat: &flat, items: &items, thumbs: K::thumbs(app, &lib) }, fns); let selection = selected(app, &panel); // The search text and the open groups are the browser's; the view is the panel's setting. let state_id = egui::Id::unique(("library-panel-state", &panel)); diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..679bd5f983 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -786,3 +786,27 @@ fn built_in_library_swatches_are_listed_in_the_ui_language() { assert!(app.session.doc().unwrap().doc.swatch("Clay 1").is_some(), "added under its own name"); crate::i18n::set_current(crate::i18n::Lang::EN); } + +/// A library panel builds its browser rows once for the library it shows, not on every frame, and builds them again +/// when the UI language changes the names it lists. +#[test] +fn library_panel_builds_its_rows_once_per_library_and_language() { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap(); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let before = row_builds(); + for _ in 0..4 { + draw_frame(&mut app, &ctx, &draw, vec![]); + } + assert_eq!(row_builds() - before, 1, "four frames of an unchanged library build its rows once"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(row_builds() - before, 2, "a new UI language builds the rows again, once"); + let painted = crate::tests_labels::shapes_text(&out); + assert!(painted.lines().any(|l| l == "Argile 1"), "the rebuilt rows are in the new language: {painted}"); +} diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 4f16980b9a..c14d6cb040 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -106,6 +106,9 @@ impl LibraryKind for SwatchLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option<String> { app.session.swatch_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } /// Ungrouped swatches, then each colour group's folder and swatches, as in the Swatches panel; the browser's Find /// narrows them. fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, Swatch>> { @@ -135,7 +138,7 @@ impl LibraryKind for SwatchLibraries { row } fn thumbs(app: &VectorcraftApp, lib: &Self::Lib) -> PatternSources { - PatternSources(lib.iter().filter_map(|w| Some((w.name.clone(), swatchlib::pattern_source(&app.session, w)?))).collect()) + PatternSources(lib.iter().filter_map(|w| swatchlib::pattern_source(&app.session, w).map(|d| (w.name.clone(), d))).collect()) } /// A pattern library's pattern, or a loaded library's, drawn from the library. fn thumb(sources: &PatternSources, cx: &ContentPainterCx<'_>, rect: Rect, w: &Swatch) { diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e8dbf1a468..cfa24aadec 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -976,6 +976,10 @@ impl LibraryKind for SymbolLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option<String> { app.session.symbol_libraries.path(id).map(str::to_string) } + /// [`get`](LibraryKind::get) wraps the library anew each time: by the library the symbols are in. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + a.len() == b.len() && a.first().zip(b.first()).is_none_or(|(a, b)| Arc::ptr_eq(&a.lib, &b.lib)) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibSymbol>> { lib.iter().map(|s| Row { name: s.name(), item: Some(s) }).collect() } From 579fa0c247c7d0f11773d930771946d0b2ef831a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 04:31:47 -0800 Subject: [PATCH 37/71] xtask: test-lint mirror leaves out reads at two entries and shared arithmetic - Two calls that differ only in the entry they name (a string or integer literal, a local, a field or an indexed element) relate two entries, as in at("B") == at("A") + 1 or bounds(&s, copy) == bounds(&s, id) + dv, and are no longer reported. - The same arithmetic on both sides (rotate_deg(-270.0) * v == rotate_deg(90.0) * v) checks that two inputs agree and is no longer reported. On main, test-lint --all reports 1 mirror hit instead of 14. --- xtask/src/test_lint.rs | 72 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..baf93450e6 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -48,7 +48,9 @@ //! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; //! * `mirror`: `assert_eq!(f(a), f(b) <op> …)`, where the expected side derives its value from a //! second call of the same function (same path) with arithmetic, so a fault in `f` moves both -//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out; +//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same +//! arithmetic on both sides and two reads that differ only in the entry they name (a string or +//! integer literal, a local or an indexed element); //! * `constant-echo`: every assertion of the test compares only constants, literals and enum //! variants; //! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the @@ -3066,22 +3068,59 @@ fn head_call(op: &str) -> Option<&str> { } } -/// `assert_eq!(f(a), f(b))`: both sides start by calling the same function, so a fault in `f` can -/// move both sides together. Identical sides are `self-compare`'s. +/// The offset of the first top-level `+`, `-`, `*` or `/` in a whitespace-free operand. +fn first_arithmetic(op: &str) -> Option<usize> { + ["+", "-", "*", "/"].iter().flat_map(|o| top_level_at(op, o)).min() +} + +/// The whitespace-free source text of the arguments of the call an operand starts with, read from +/// the unmasked source so string literals keep their text. +fn head_args(f: &File, (from, to): (usize, usize)) -> Option<Vec<String>> { + let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; + let close = matching(&f.m, open)?; + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(&f.src[a..b])).collect()) +} + +/// An argument that names an entry rather than a quantity: a string or integer literal, or a local, +/// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). +fn key_like(arg: &str) -> bool { + let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); + match arg.as_bytes().first() { + Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), + Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), + None => false, + } +} + +/// `assert_eq!(f(a), f(b) <op> …)`: the expected side derives its value from a second call of the +/// same function with arithmetic, so a fault in `f` can move both sides together. Identical sides +/// are `self-compare`'s. Left out: the same arithmetic on both sides (`f(a) * v == f(b) * v` +/// checks that two inputs agree, as a periodicity check does), and two reads at different entries +/// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. fn mirrors(v: &View) -> Vec<Hit> { v.asserts .iter() .filter(|a| a.name.ends_with("_eq")) .filter_map(|a| { - let (l, r) = (norm(&v.file.m[a.args.first()?.0..a.args.first()?.1]), norm(&v.file.m[a.args.get(1)?.0..a.args.get(1)?.1])); + let (lr, rr) = (*a.args.first()?, *a.args.get(1)?); + let (l, r) = (norm(&v.file.m[lr.0..lr.1]), norm(&v.file.m[rr.0..rr.1])); let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let name = head_call(l)?; - // The expected side derives its value from a second call with arithmetic; two calls - // compared as they are check that two inputs agree, which is a real check. - let derived = ["+", "-", "*", "/"].iter().any(|op| !top_level_at(r, op).is_empty()); + // Two calls compared as they are check that two inputs agree, which is a real check. + let derived = match (first_arithmetic(l), first_arithmetic(r)) { + (_, None) => false, + (Some(i), Some(j)) => l[i..] != r[j..], + (None, Some(_)) => true, + }; let last = name.rsplit("::").next().unwrap_or(name); - (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)) - .then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { + return None; + } + let (la, ra) = (head_args(v.file, lr)?, head_args(v.file, rr)?); + let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); + let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); + (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) }) .collect() } @@ -5279,6 +5318,21 @@ mod tests { assert_eq!(only("mirror", ne), [], "two inputs that must differ"); let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror scaling is linear by definition\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); + let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; + assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + } + + #[test] + fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { + let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; + assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let offset = + "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; + assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); + let period = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * v);\n}\n"; + assert_eq!(only("mirror", period), [], "the same arithmetic on both sides"); + let tails = "#[test]\nfn t() {\n assert_eq!(rotate_deg(-270.0) * v, rotate_deg(90.0) * w);\n}\n"; + assert_eq!(only("mirror", tails), [(3, "mirror")], "different arithmetic on each side still derives one from the other"); } #[test] From 07acf0bf370b7e1631a8e039997ac2898d5f4069 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:50:07 +0530 Subject: [PATCH 38/71] Keep Glyphs menus open across unrelated font changes --- crates/ui-egui/src/panels/glyphs.rs | 51 +++++++++++++---------- crates/ui-egui/src/panels/glyphs/tests.rs | 10 ++++- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index 4d60dd59ef..ad1bc48c1f 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -24,6 +24,7 @@ //! as Entire Font shows them. use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; use craft::font_manager::glyphs::{CATEGORIES, CellInfo, GlyphCell, GlyphCellMenu, GlyphSource, GlyphsPanel, GlyphsWords}; @@ -299,11 +300,11 @@ fn insert(app: &mut VectorcraftApp, ch: char) -> bool { /// character, all read when it is made, so it borrows nothing from the app. Every method uses the /// held face whatever family and style it is given: the face of the canvas row or of the selected /// text can be an instance of variable axes that no family and style name reaches. -pub(crate) struct VcGlyphs<'a> { - db: &'a FontDb, +pub(crate) struct VcGlyphs { family: String, style: String, face: Option<Arc<FontFace>>, + revision: u64, /// What a glyph no character maps can do to the selected character; none for a face without one /// and in Alternates for Selection. fit: Option<Fit>, @@ -313,7 +314,7 @@ pub(crate) struct VcGlyphs<'a> { empty: Option<String>, } -impl VcGlyphs<'static> { +impl VcGlyphs { /// The source of the panel: the browsed face, or the face of the selected character's alternates /// in Alternates for Selection. pub(crate) fn of(app: &mut VectorcraftApp) -> Self { @@ -321,44 +322,42 @@ impl VcGlyphs<'static> { if app.ui.glyphs_panel.category == ALTERNATES { return match alternates_listing(app) { Ok(listing) => VcGlyphs { - db: FontDb::global(), family: listing.face.family.clone(), style: listing.face.style.clone(), face: Some(listing.face.clone()), + revision: listing.revision(), fit: None, listing: Some(listing), empty: None, }, - Err(note) => VcGlyphs { db: FontDb::global(), family, style, face: None, fit: None, listing: None, empty: Some(note) }, + Err(note) => VcGlyphs { family, style, face: None, revision: 0, fit: None, listing: None, empty: Some(note) }, }; } let fit = face.as_ref().map(|f| Fit::of(app, f)); let empty = face.is_none().then(|| tl!("No fonts are available.").to_string()); - VcGlyphs { db: FontDb::global(), family, style, face, fit, listing: None, empty } + let revision = face.as_ref().map_or(0, |face| u64::from(face.id())); + VcGlyphs { family, style, face, revision, fit, listing: None, empty } } /// The source of `face` alone: it draws glyphs and describes nothing about the selection. fn bare(face: Arc<FontFace>) -> Self { VcGlyphs { - db: FontDb::global(), family: face.family.clone(), style: face.style.clone(), + revision: u64::from(face.id()), face: Some(face), fit: None, listing: None, empty: None, } } -} - -impl VcGlyphs<'_> { /// The family and style the panel shows. fn font(&self) -> (&str, &str) { (&self.family, &self.style) } } -impl GlyphSource for VcGlyphs<'_> { +impl GlyphSource for VcGlyphs { fn cells(&self, _family: &str, _style: &str, category: &str) -> Vec<GlyphCell> { let Some(face) = &self.face else { return vec![] }; if category == ALTERNATES { @@ -398,7 +397,9 @@ impl GlyphSource for VcGlyphs<'_> { } fn revision(&self) -> u64 { - self.db.generation() + // The grid uses this for both cached cells and open glyph-ID menus. Changes + // elsewhere in the font catalog leave the displayed face and its glyph IDs valid. + self.revision } fn categories(&self, _family: &str, _style: &str) -> Vec<(String, String)> { @@ -485,11 +486,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if out.font_changed { app.ui.glyphs_font = Some((family, style)); } - let menu_cell = out - .menu - .as_ref() - .filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)) - .map(|menu| menu.cell); + let menu_cell = out.menu.as_ref().filter(|menu| !out.font_changed && cell_menu(ui, &source, can_insert, menu)).map(|menu| menu.cell); if let Some(cell) = menu_cell.or(out.activated) { activate(app, cell); } @@ -499,7 +496,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// Offer the action for the clicked cell using the grid's face and text context for this pass. -fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphCellMenu) -> bool { +fn cell_menu(ui: &mut Ui, source: &VcGlyphs, can_insert: bool, menu: &GlyphCellMenu) -> bool { let Some(face) = &source.face else { return false }; let (label, enabled) = match menu.cell { GlyphCell::Char(c) => (tl!("Insert Glyph"), source.listing.is_none() && gid_of(face, c).is_some()), @@ -512,10 +509,7 @@ fn cell_menu(ui: &mut Ui, source: &VcGlyphs<'_>, can_insert: bool, menu: &GlyphC } _ => return false, }; - Menu::context(label, &menu.opener) - .show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran) - .inner - .unwrap_or(false) + Menu::context(label, &menu.opener).show(ui, |ui, _| MenuItem::new(label).enabled(can_insert && enabled).show(ui).ran).inner.unwrap_or(false) } /// A double-click or Enter on `cell`: insert the character (its letter for an Arabic presentation @@ -648,6 +642,17 @@ struct Listing { } impl Listing { + /// The visible alternates can change at another text target in the same face. + fn revision(&self) -> u64 { + let mut revision = DefaultHasher::new(); + (self.face.id(), self.id, self.bytes, self.variants.len()).hash(&mut revision); + for variant in &self.variants { + variant.gid.hash(&mut revision); + } + // Face-only revisions are u32 IDs. Keep a listing in a separate range. + revision.finish() | (1 << 63) + } + /// Draw the character with glyph `gid` of the listing, as one undo step. fn apply(&self, app: &mut VectorcraftApp, gid: u32) { if let Some(variant) = self.variants.iter().find(|v| v.gid == gid) { @@ -775,7 +780,7 @@ impl OnCanvas { } /// The source that draws the offered glyphs ([`Self::face`]). - pub fn source(&self) -> VcGlyphs<'static> { + pub fn source(&self) -> VcGlyphs { VcGlyphs::bare(self.face.clone()) } diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index a4f6635324..8a797f4fec 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -43,7 +43,7 @@ fn browsed(app: &VectorcraftApp) -> (String, String) { } /// The panel's cell source, as the panel builds it. -fn source(app: &mut VectorcraftApp) -> VcGlyphs<'static> { +fn source(app: &mut VectorcraftApp) -> VcGlyphs { VcGlyphs::of(app) } @@ -1153,7 +1153,7 @@ fn insert_glyph_is_disabled_without_a_text_target() { /// In Alternates for Selection a right-click offers Apply Alternate in one undo step. #[test] fn right_clicking_an_alternate_cell_offers_apply_alternate() { - use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid, thai_font}; FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); @@ -1170,6 +1170,12 @@ fn right_clicking_an_alternate_cell_offers_apply_alternate() { panel.secondary_click(&name); assert!(panel.menu_item_enabled("Apply Alternate")); assert!(!panel.shows("Insert Glyph"), "an alternate cell offers Apply Alternate"); + // Registering a different family between the menu's opening and the click + // must leave its glyph-ID target valid. + let unrelated = thai_font("VectorCraft Glyph Menu Unrelated Fixture", true).expect("the unrelated test font builds"); + assert!(FontDb::global().add_font(unrelated) > 0); + panel.frame(); + assert!(panel.menu_item_enabled("Apply Alternate")); panel.click_menu_item("Apply Alternate"); let app = panel.app(); assert_eq!(undo_len(&app), undo + 1, "one undo step"); From 0326297ddf1a4d22f320c50050f9cd956f4fa3c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 06:26:45 -0800 Subject: [PATCH 39/71] Tests: hold the clock still in the heavy filter shortcut test a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item read the wall clock. When more than 0.4 s passed between the frame that started the heavy run and the next one, the run's progress window opened and took the next key, so the filter with parameters did not open its dialog. On a loaded machine this failed some runs of the same tree. The test now sets the app's test clock to a fixed time, as the export_progress tests do, so the progress window stays closed however slowly the frames run. --- crates/ui-egui/src/shortcuts/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index d22d8e9eb6..9b441b1f67 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1838,6 +1838,9 @@ fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { // the key is still running when Cancel stops it, however long the frames take. let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build()); + // The clock stands still: the run's progress window, which opens once the run is old enough + // and takes the keys, stays closed however slowly the frames run. + app.now_override = Some(0.0); app.session.allow_plugin_grants_from_requests(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); From d61d946a3df86a41ff24b6fb2648c5b725e29533 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:59:45 +0530 Subject: [PATCH 40/71] Color Themes: add a context menu to saved theme rows --- crates/ui-egui/src/panels/color_themes.rs | 106 ++++++++++++++++------ docs/target-app-parity.md | 1 + 2 files changed, 80 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 3d1b32f037..7ba34fe65a 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -10,7 +10,7 @@ // framework crates' layout (racheck-fw); none of them is imported anywhere else in the app yet. use std::borrow::Cow; -use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange}; +use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection, SelectionChange, keyed}; use craft::color_ui::ui::{ChannelRow, ColorPanelMode, HarmonyWheel}; use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; @@ -19,7 +19,7 @@ use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; use craft::ui::pickers::Select; use craft::ui::primitives::IconSpec; @@ -592,44 +592,45 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else if rows.is_empty() { Notice::new(Tone::Neutral, tl!("No matches.")).show(ui); } else { - let names: Vec<String> = rows.iter().map(|(n, _)| n.clone()).collect(); - let mut selection = app - .ui - .color_themes_panel - .picked - .as_ref() - .and_then(|p| names.iter().position(|n| n == p)) - .map_or_else(Selection::default, Selection::single); - let out = List::new(tl!("My Themes")).select(craft::ui::contract::SelectMode::Single).selection(Bind::bound(&mut selection)).show_items( - ui, - &Names(&names), - &mut |key, _| { - let colors = rows.get(*key).map(|(_, c)| c.clone()).unwrap_or_default(); - let name = names.get(*key).cloned().unwrap_or_default(); - ListRow::new(name).thumb(ThumbSize::Small, move |cx, rect| { + let document = app.session.active().map(|st| st.uid); + let selection = picked(app).map_or_else(Selection::default, Selection::single); + let out = List::new(tl!("My Themes")) + .id(ui.scope_id().with(("my-themes", document))) + .select(craft::ui::contract::SelectMode::Single) + .selection(Bind::given(selection)) + .row_menu() + .show_items(ui, &keyed(&rows, |(name, _)| name.clone()), &mut |name, icx| { + let colors = rows[icx.at].1.clone(); + ListRow::new(name.clone()).thumb(ThumbSize::Small, move |cx, rect| { let w = rect.width() / colors.len().max(1) as f32; cx.data_shapes(colors.iter().enumerate().map(|(i, c)| { egui::Shape::rect_filled(Rect::from_min_size(rect.min + vec2(i as f32 * w, 0.0), vec2(w, rect.height())), 0.0, c32(c)) })); }) - }, - ); + }); for event in out.events { match event { CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => { - if let Some(name) = keys.last().and_then(|k| names.get(*k)) { - app.ui.color_themes_panel.picked = Some(name.clone()); - } + app.ui.color_themes_panel.picked = keys.last().cloned(); } + CollectionEvent::ContextMenu(request) => app.ui.color_themes_panel.picked = Some(request.key), // Enter and a double click edit the theme. - CollectionEvent::Activate(key) => { - if let Some(name) = names.get(key) { - edit_saved(app, name); - } - } + CollectionEvent::Activate(name) => edit_saved(app, &name), _ => {} } } + if let Some(request) = out.menu + && app.ui.color_themes_panel.tab == MY_THEMES + && app.ui.color_themes_panel.picked.as_ref() == Some(&request.key) + { + Menu::context(request.key, &out.response).show(ui, |ui, _| { + for (id, label) in [(EDIT, tl!("Edit Theme")), (ADD_TO_SWATCHES, tl!("Add to Swatches")), (DELETE, tl!("Delete Theme"))] { + if MenuItem::new(label).enabled(enabled(app, id)).show(ui).ran { + run(app, id, &Value::Null); + } + } + }); + } } let labels = vec![Label::from(tl!("Delete theme")), Label::from(tl!("Add to Swatches")), Label::from(tl!("Edit theme"))]; footer(app, ui, &[DELETE, ADD_TO_SWATCHES, EDIT], &["trash-2", "dc-folder", "pencil"], labels); @@ -831,6 +832,57 @@ mod tests { assert_eq!(picked(&app), None); } + #[test] + fn the_theme_menu_follows_its_row_when_the_list_is_filtered() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + app.ui.color_themes_panel.picked = Some("Forest".into()); + let mut panel = Panel::new(app, show); + panel.secondary_click("Harvest"); + assert_eq!(picked(&panel.app()).as_deref(), Some("Harvest")); + panel.app().ui.color_themes_panel.find = "vest".into(); + panel.frame(); + panel.click_menu_item("Delete Theme"); + assert_eq!(themes(&panel.app()).iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["Harbor", "Forest"]); + } + + #[test] + fn keyboard_theme_menu_uses_the_focused_row_without_a_document() { + use crate::tests::panel_harness::Panel; + + let mut app = three_themes(""); + assert!(app.session.close_document(0)); + let mut panel = Panel::new(app, show); + panel.click("Forest"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled("Edit Theme")); + assert!(panel.menu_item_enabled("Delete Theme")); + assert!(!panel.menu_item_enabled("Add to Swatches")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + assert!(panel.focused("Forest")); + } + + #[test] + fn the_theme_menu_closes_when_its_row_disappears_or_the_document_changes() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(three_themes(""), show); + panel.secondary_click("Harbor"); + assert!(panel.menu_item_enabled("Edit Theme")); + panel.app().ui.color_themes_panel.find = "Forest".into(); + panel.frame(); + assert!(!panel.shows_role("Edit Theme", Role::MENU_ITEM)); + panel.secondary_click("Forest"); + assert!(panel.menu_item_enabled("Add to Swatches")); + panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + panel.frame(); + assert!(!panel.shows_role("Add to Swatches", Role::MENU_ITEM)); + } + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in /// the name, in their saved order; it reads names only, and its text is plain text. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5f5f9644d5..1eac724072 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2203,6 +2203,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52):** VectorCraft's own press models, computed when first used from the characterization data Fogra publishes (<https://fogra.org/en/downloads/work-tools/characterisation-data>), which ships unmodified: the measured paper, solids and overprints, a tone curve fitted to each ink's ramp, and a smoothed Lab correction lattice fitted to all 1,617 patches. The models reproduce the patches within a mean ΔE2000 of 0.04 (largest 0.37), and patches left out of the fit within 0.15 to 0.17 (largest 1.67). A PDF/X output intent made with one embeds the profile; with the condition identifier left blank it names `FOGRA51` or `FOGRA52`, in the `http://www.color.org` registry unless the settings give a registry, and an identifier the settings give is written as given. The 300% ink limit and black generation are VectorCraft's own values. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **My Themes row menu:** Opening a saved theme's row menu selects it and offers Edit Theme, Add to Swatches and Delete Theme. Add to Swatches requires an active document. - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. From 3d2b663b9e61206d2ef31b6ad4f75f2af0719c62 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 06:27:27 -0800 Subject: [PATCH 41/71] xtask: test-lint never-run follows #[path] modules and multiline gates never-run now finds the files that load a module through `#[path]`, including a sibling such as `graphics.rs` loading `tests_graphics.rs`, and follows them in both `--all` and changed-file mode. A changed file now reaches every file it loads, directly or through other modules, so a `cfg` added to its `mod` declaration flags the unchanged child's tests. - Every route to a module counts: inline-module routes, `#[path]` routes and several routes from one file are joined, each with its own ancestors, and a crate root keeps its own route. - A default `mod x;` matches only the file it really loads. - Every line of a multiline `cfg` attribute counts as a gate line, for the test's own gates and for the parent declarations. - The base comparison reads `#[path]` declarations from the base tree, so a moved declaration is not reported as newly off. --- xtask/src/test_lint.rs | 675 +++++++++++++++++++++++++++++++++++------ 1 file changed, 579 insertions(+), 96 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index baf93450e6..dc10c00fe7 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -81,7 +81,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -272,20 +272,43 @@ fn gate_changed(gates: Option<&Gates>, changed: &BTreeMap<String, Option<BTreeSe .any(|(parent, lines)| changed.get(parent).is_some_and(|c| c.as_ref().is_none_or(|set| lines.iter().any(|l| set.contains(l))))) } +/// Whether a change touches the declarations that gate the module file `path` now +/// ([`gate_changed`]), or any file that declared it at the base: an edit there can remove a way for +/// its tests to run, and the base lines may no longer match. +fn route_gate_changed( + path: &str, + gates: Option<&Gates>, + base_gates: Option<&Gates>, + base_overrides: &Overrides, + changed: &BTreeMap<String, Option<BTreeSet<usize>>>, +) -> bool { + gate_changed(gates, changed) + || base_gates.is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent))) + || base_overrides.get(path).is_some_and(|routes| routes.iter().any(|(parent, _)| changed.contains_key(parent))) +} + /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. fn read_small(root: &Path, path: &str) -> Option<String> { let full = root.join(path); (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } +/// Cache successful and missing reads for one source tree. +fn cached_read(read: impl Fn(&str) -> Option<String>) -> impl Fn(&str) -> Option<String> { + let cache = RefCell::new(HashMap::<String, Option<String>>::new()); + move |path| cache.borrow_mut().entry(path.to_owned()).or_insert_with(|| read(path)).clone() +} + pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let opts = Options::parse(args)?; + let read_work = cached_read(|p| read_small(root, p)); let repo = crate::repo_files(root)?; let ci_env = ci_env(root, &repo)?; let files: Vec<String> = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let overrides = path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))); + let module_cfgs = module_cfgs(&files, &read_work, &overrides); let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec<Hit> = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); @@ -297,31 +320,27 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let crates: BTreeSet<String> = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec<String> = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec<String> = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn - // their tests off without a change to them. - let module_dirs: Vec<String> = present - .iter() - .map(|p| { - let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); - if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } - }) - .collect(); - let below: Vec<String> = - files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + // Files that load a module through `#[path]`, found with `git grep` (untracked files included) + // instead of reading the tree. + let overrides = discover_path_overrides(root, None, &read_work); + let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); + let base_overrides = discover_path_overrides(root, Some(&base), &read_base); + // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` + // declaration can turn their tests off without a change to them. + let below: Vec<String> = descendants(&present, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec<String> = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; // The gates the parent declarations gave at the base: a parent edit counts against a child's // test only when the test ran in CI before it. - let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_gates = module_gates(&gated, &read_base, &base_overrides); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); + let newly_off = |path: &str, src: &str, hit: &Hit| !already_off(&lint_file(path, src, &base_ctx), hit); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) @@ -332,13 +351,50 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { - let Some(src) = read_small(root, path) else { continue }; + for path in below.iter().filter(|p| route_gate_changed(p, gates.get(*p), base_gates.get(*p), &base_overrides, &changed)) { + let Some(src) = read_work(path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } +/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the +/// test of `hit`. Tests of one name in different inline modules are told apart by their line. +fn already_off(base: &[Hit], hit: &Hit) -> bool { + base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + +/// The directory holding the modules that the file `p` declares by name: its own directory for +/// `mod.rs`, `lib.rs` and `main.rs`, and the directory named after it otherwise. +fn module_dir(p: &str) -> String { + let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); + if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } +} + +/// The files of `files` that the files `start` load, directly or through modules in between: the +/// files under their module directories and the files their current or base `#[path]` declarations load. +fn descendants(start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides) -> Vec<String> { + let mut seen: BTreeSet<String> = start.iter().cloned().collect(); + let mut frontier: Vec<String> = start.to_vec(); + let mut out = vec![]; + while !frontier.is_empty() { + let dirs: Vec<String> = frontier.iter().map(|p| module_dir(p)).collect(); + let next: Vec<String> = files + .iter() + .filter(|p| !seen.contains(*p)) + .filter(|p| { + dirs.iter().any(|d| p.starts_with(d.as_str())) + || overrides.get(*p).into_iter().chain(base_overrides.get(*p)).flatten().any(|(parent, _)| frontier.contains(parent)) + }) + .cloned() + .collect(); + seen.extend(next.iter().cloned()); + out.extend(next.iter().cloned()); + frontier = next; + } + out +} + /// The command line: `--all`, `--base <rev>`. #[derive(Debug, Default, PartialEq)] struct Options { @@ -3365,6 +3421,8 @@ fn cfg_value(p: &str, t: &Target) -> Option<bool> { } } if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { + let arg = arg.trim(); + let arg = arg.strip_suffix(',').unwrap_or(arg).trim_end(); return cfg_value(arg, t).map(|v| !v); } // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. @@ -3455,8 +3513,8 @@ fn pred_text(src: &[u8]) -> String { } /// The predicates of the `cfg` attributes ([`cfg_attrs`]) whose item holds `pos`, each with the -/// offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// offsets where its attribute starts and ends. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for CfgAttr { pred, at, end, inner } in cfg_attrs(m, src, 0, m.len()) { let span = if inner { @@ -3472,7 +3530,7 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { } }; if span.0 <= pos && pos <= span.1 { - out.push((pred, at)); + out.push((pred, at, end)); } } out @@ -3480,10 +3538,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { /// The module name a file declares and the files that may declare it with `mod <name>;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples`). +/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `src` holds modules, not test targets. fn module_parent(path: &str) -> Option<(&str, Vec<String>)> { let (dir, file) = path.rsplit_once('/')?; - let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin"); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } @@ -3511,6 +3571,10 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>, let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let mut default_dir = if mod_rs { dir.to_owned() } else { join_path(dir, file.strip_suffix(".rs").unwrap_or(file)) }; + for seg in want.chain { + default_dir = join_path(&default_dir, seg); + } let (mut each, mut at_lines) = (vec![], vec![]); for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); @@ -3520,19 +3584,11 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>, } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => { - // A `#[path]` outside inline modules is relative to the file's directory; inside them, - // to the inline modules' directory under the file's module. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + Some(rel) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path, + None => { + &m[start..end] == want.name.as_bytes() + && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } - None => &m[start..end] == want.name.as_bytes(), }; if !loads { continue; @@ -3540,11 +3596,12 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>, // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec<CfgAttr> = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); at_lines.push(lines.of(at)); - at_lines.extend(attrs.iter().map(|a| lines.of(a.at))); + // Every line of a multiline attribute counts: an edit inside its predicate changes it. + at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec<String> = attrs.into_iter().map(|a| a.pred).collect(); - for (p, a) in cfgs_over(&m, src.as_bytes(), at) { + for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); - at_lines.push(lines.of(a)); + at_lines.extend(lines.of(a)..=lines.of(e)); } each.push(preds); } @@ -3556,6 +3613,90 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>, Some((preds, at_lines)) } +/// The file a `#[path = "<rel>"]` declaration in the file `dir/file` loads. Outside inline modules +/// `rel` is relative to the file's directory; inside them (`chain`, outermost first), to the inline +/// modules' directory under the file's module. +fn override_path(dir: &str, file: &str, mod_rs: bool, chain: &[String], rel: &str) -> String { + let mut base = dir.to_owned(); + if !chain.is_empty() && !mod_rs { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + +/// The files that `#[path]` declarations in `src`, the file `parent`, load, each with the inline +/// modules its declaration sits in. +fn path_children(src: &str, parent: &str) -> Vec<(String, Vec<String>)> { + let m = mask(src); + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); + let mut out = vec![]; + for at in words(&m, b"mod", 0, m.len()) { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + continue; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + let chain = inline_mods(&m, at); + out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); + } + } + out +} + +/// The files that load a module file through `#[path]`, keyed by the file they load: a sibling such +/// as `graphics.rs` loading `tests_graphics.rs` is not among the files [`module_parent`] names. +type Overrides = HashMap<String, Vec<(String, Vec<String>)>>; + +/// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. +fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides { + let with_path = match base { + Some(base) => git(root, &["grep", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + } + .unwrap_or_default(); + listed_path_overrides(&with_path, base, read) +} + +/// Read paths from `git grep -l`, removing the revision prefix for a base-tree listing. +fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides { + let prefix = base.map(|b| format!("{b}:")); + let sources: Vec<(String, String)> = list + .lines() + .filter_map(|p| match &prefix { + Some(prefix) => p.strip_prefix(prefix), + None => Some(p), + }) + .filter(|p| is_scanned(p)) + .filter_map(|p| read(p).map(|s| (p.to_owned(), s))) + .collect(); + path_overrides(sources.iter().map(|(p, s)| (p.as_str(), s.as_str()))) +} + +/// [`Overrides`] for the files `sources`, as `(path, source)` pairs. +fn path_overrides<'a>(sources: impl IntoIterator<Item = (&'a str, &'a str)>) -> Overrides { + let mut out: Overrides = HashMap::new(); + for (parent, src) in sources { + if !src.contains("path") { + continue; + } + for (child, chain) in path_children(src, parent) { + // One entry per parent and inline modules: [`declared_cfgs`] joins the declarations of + // one file in one module. + let routes = out.entry(child).or_default(); + if !routes.iter().any(|(p, c)| p == parent && *c == chain) { + routes.push((parent.to_owned(), chain)); + } + } + } + out +} + /// The string value of a `#[path = "…"]` attribute in `m[from..to]`. fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> { words(m, b"path", from, to).into_iter().find_map(|at| { @@ -3604,8 +3745,8 @@ fn inline_mods(m: &[u8], at: usize) -> Vec<String> { /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashMap<String, Vec<String>> { - module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides) -> HashMap<String, Vec<String>> { + module_gates(paths, read, overrides).into_iter().map(|(p, g)| (p, g.preds)).collect() } /// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares @@ -3617,62 +3758,85 @@ struct Gates { } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that -/// may declare its module and, when none does, in the files above them through inline modules -/// (`mod platform { mod child; }` loads `platform/child.rs`). -fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option<String>) -> HashMap<String, Gates> { - let mut out = HashMap::new(); - for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec<String> = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec<String> = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { - out.insert(path.clone(), gates); - } +/// may declare its module and in the files above them through inline modules +/// (`mod platform { mod child; }` loads `platform/child.rs`), and in the files of `overrides` that +/// load it through `#[path]`. +fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides) -> HashMap<String, Gates> { + let read = cached_read(read); + paths + .iter() + .filter_map(|path| { + let gates = module_gate(path, &read, overrides, 0); + (!gates.preds.is_empty()).then(|| (path.clone(), gates)) + }) + .collect() +} + +/// Resolve each route's ancestors before joining routes, with a bound for cyclic module paths. +fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Overrides, depth: usize) -> Gates { + let mut gates = Gates::default(); + if depth >= 16 { + return gates; } - out + let by_path = overrides.get(at).map_or(&[][..], Vec::as_slice); + // A crate root runs independently of any module declarations that also load it. + let Some((name, mut candidates)) = module_parent(at) else { return gates }; + let name = name.to_owned(); + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return gates; + }; + let mut chain: Vec<String> = vec![]; + let mut found = vec![]; + for _ in 0..4 { + let want = Loaded { path: at, name: &name, chain: &chain }; + // Every file that loads the module is another way in (a library and a binary root + // can both load it): its tests are off only when every one of them leaves them out. + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + if chain.is_empty() { + for (c, inline) in by_path { + // A candidate was read with no inline modules; another route through the + // same file still counts. + if inline.is_empty() && candidates.contains(c) { + continue; + } + let want = Loaded { path: at, name: &name, chain: inline }; + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))); + } + } + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + let mut each = vec![]; + for (parent, (mut preds, lines)) in found { + let ancestors = module_gate(&parent, read, overrides, depth + 1); + preds.extend(ancestors.preds); + gates.sources.push((parent, lines)); + gates.sources.extend(ancestors.sources); + each.push(preds); + } + gates.preds = match each.len() { + 0 => vec![], + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::<Vec<_>>().join(","))], + }; + gates } /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option<Hit> { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); - // A change to an attribute that turns the test off counts as a change to the test. - let attr_lines: Vec<usize> = local.iter().map(|&(_, at)| v.file.lines.of(at)).collect(); - let mut preds: Vec<String> = local.into_iter().map(|(p, _)| p).collect(); + // A change to an attribute that turns the test off counts as a change to the test, on any line + // of a multiline attribute. + let attr_lines: Vec<usize> = local.iter().flat_map(|&(_, at, end)| v.file.lines.of(at)..=v.file.lines.of(end)).collect(); + let mut preds: Vec<String> = local.into_iter().map(|(p, _, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -5366,6 +5530,18 @@ mod tests { assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); } + #[test] + fn never_run_accepts_trailing_commas_in_cfg_predicates() { + for pred in ["not(unix,)", "not( unix , )", "all(not(unix,),)", "any(not(unix,),)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [(3, "never-run")], "{pred}"); + } + for pred in ["all(unix,)", "any(unix,)"] { + let src = format!("#[cfg({pred})]\n#[test]\nfn t() {{\n assert_eq!(f(), 1);\n}}\n"); + assert_eq!(only("never-run", &src), [], "{pred}"); + } + } + #[test] fn never_run_tests_are_compiled_out_on_every_ci_target() { let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; @@ -5391,6 +5567,27 @@ mod tests { assert_eq!(only("never-run", other), [], "a cfg on another item"); } + #[test] + fn module_gates_reads_each_candidate_once() { + let paths: Vec<String> = (0..32).map(|i| format!("crates/x/src/parent/child{i}.rs")).collect(); + let parent = (0..32).map(|i| format!("mod child{i};\n")).collect::<String>(); + let files = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n"), ("crates/x/src/parent.rs", parent.as_str())]; + let reads = RefCell::new(HashMap::<String, usize>::new()); + let read = |p: &str| { + *reads.borrow_mut().entry(p.to_owned()).or_default() += 1; + files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()) + }; + let gates = module_gates(&paths, &read, &Overrides::new()); + assert_eq!(gates.len(), paths.len(), "every child inherits the parent gate"); + let reads = reads.borrow(); + assert_eq!(reads.get("crates/x/src/lib.rs"), Some(&1), "a shared ancestor"); + assert_eq!(reads.get("crates/x/src/parent.rs"), Some(&1), "a shared parent"); + assert_eq!(reads.get("crates/x/src/parent/mod.rs"), Some(&1), "a missing candidate"); + for (path, count) in reads.iter() { + assert_eq!(*count, 1, "candidate {path}"); + } + } + #[test] fn never_run_follows_the_cfg_of_the_mod_declaration() { let files: HashMap<&str, &str> = [ @@ -5405,7 +5602,7 @@ mod tests { .into_iter() .map(String::from) .collect(); - let cfgs = module_cfgs(&paths, &read); + let cfgs = module_cfgs(&paths, &read, &Overrides::new()); assert_eq!(cfgs.get("crates/x/src/mac.rs").map(Vec::as_slice), Some(&["target_os=\"macos\"".to_owned()][..])); assert!(cfgs.contains_key("crates/x/src/mac/inner.rs"), "inherited through mac.rs"); assert!(!cfgs.contains_key("crates/x/src/plain.rs") && !cfgs.contains_key("crates/x/tests/it.rs")); @@ -5461,13 +5658,299 @@ mod tests { let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod plain;\n#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); let lib = |lines: &[usize]| -> BTreeMap<String, Option<BTreeSet<usize>>> { [("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))].into_iter().collect() }; assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[2])), "the cfg line"); assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "the declaration line"); assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[1])), "another declaration"); + let multiline: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod child;\nmod plain;\n"), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| multiline.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[3])), "a line inside a multiline predicate"); + assert!(!gate_changed(gates.get("crates/x/src/child.rs"), &lib(&[6])), "another declaration"); + let enclosing: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod platform {\n mod child;\n}\nmod plain;\n"), + ("crates/x/src/platform/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| enclosing.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/platform/child.rs".to_owned()], &read, &Overrides::new()); + assert!(gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[3])), "a line inside the inline module's predicate"); + assert!(!gate_changed(gates.get("crates/x/src/platform/child.rs"), &lib(&[8])), "a declaration outside the inline module"); + } + + #[test] + fn never_run_follows_a_path_override_in_a_sibling_file() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod solids;\n"), + ("crates/x/src/solids/mod.rs", "mod graphics;\n"), + ("crates/x/src/solids/graphics.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"tests_graphics.rs\"]\nmod tests;\n"), + ("crates/x/src/solids/tests_graphics.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/solids/tests_graphics.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&child), &read, &overrides); + assert_eq!(gates.get(&child).map(|g| g.preds.clone()), Some(vec!["target_os=\"macos\"".to_owned()])); + let changed: BTreeMap<String, Option<BTreeSet<usize>>> = + [("crates/x/src/solids/graphics.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(&child), &changed), "a cfg added to the sibling's declaration"); + } + + #[test] + fn never_run_keeps_crate_roots_independent_of_path_overrides() { + for child in [ + "crates/x/tests/shared.rs", + "crates/x/src/lib.rs", + "crates/x/src/main.rs", + "crates/x/src/bin/tool.rs", + "crates/x/examples/demo.rs", + "crates/x/benches/speed.rs", + "crates/x/build.rs", + ] { + let declaration = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod shared;\n", child.strip_prefix("crates/x/").unwrap()); + let files = [("crates/x/other.rs", declaration.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the crate root runs independently: {child}"); + let gated = format!("#[cfg(target_os = \"macos\")]\n{test}"); + assert_eq!(hits_in(child, &gated, &ctx), [(3, "never-run")], "the root's own cfg still applies: {child}"); + } + } + + #[test] + fn a_namesake_already_off_does_not_hide_a_newly_off_test() { + let src = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let path = "crates/x/src/child.rs"; + let base = lint_file(path, src, &ctx()); + let now = + lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); + } + + #[test] + fn never_run_follows_a_tests_module_directory_under_src() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod tests;\n"), ("crates/x/src/tests.rs", "mod fonts;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/tests/fonts.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); + assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + } + + #[test] + fn path_override_discovery_accepts_attribute_whitespace_in_both_trees() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-path-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let files = [ + ("crates/x/src/a.rs", "#[cfg(target_os = \"macos\")]\n#[ path = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[\npath = \"shared.rs\"]\nmod s;\n"), + ("crates/x/src/decoy.rs", "// path is not a module attribute\nmod other;\n"), + ]; + for (path, src) in files { + std::fs::write(root.join(path), src).unwrap(); + } + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + for revision in [None, Some(base.as_str())] { + let read = |p: &str| match revision { + Some(base) => git(&root, &["show", &format!("{base}:{p}")]).ok(), + None => read_small(&root, p), + }; + let overrides = discover_path_overrides(&root, revision, &read); + let child = "crates/x/src/shared.rs"; + let parents: BTreeSet<&str> = overrides.get(child).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, [files[0].0, files[1].0].into_iter().collect(), "both whitespace forms: {revision:?}"); + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [(2, "never-run")], "the discovered gates apply: {revision:?}"); + } + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn never_run_joins_inline_and_override_routes() { + for (lib, child) in [ + ("mod platform { mod child; }\nmod a;\n", "crates/x/src/platform/child.rs"), + ("mod platform { mod nested { mod child; } }\nmod a;\n", "crates/x/src/platform/nested/child.rs"), + ] { + let a = format!("#[cfg(target_os = \"macos\")]\n#[path = \"{}\"]\nmod other;\n", child.strip_prefix("crates/x/src/").unwrap_or(child)); + let files = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", a.as_str())]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &ctx), [], "the ungated inline route runs it"); + for parent in ["crates/x/src/lib.rs", "crates/x/src/a.rs"] { + let changed = [(parent.to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "both routes contribute their source lines: {parent}"); + } + } + } + + #[test] + fn never_run_keeps_default_and_override_files_separate() { + let files = [ + ("crates/x/src/lib.rs", "mod a;\n"), + ("crates/x/src/a.rs", "mod shared;\n#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod other;\n"), + ]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let paths = ["crates/x/src/shared.rs".to_owned(), "crates/x/src/a/shared.rs".to_owned()]; + let gates = module_gates(&paths, &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&paths[0], test, &ctx), [(2, "never-run")], "only the macOS override loads this file"); + assert_eq!(hits_in(&paths[1], test, &ctx), [], "the default declaration loads the file under a/"); + let changed = [("crates/x/src/a.rs".to_owned(), Some([1].into_iter().collect()))].into_iter().collect(); + assert!(!gate_changed(gates.get(&paths[0]), &changed), "the default declaration belongs to the other file"); + } + + #[test] + fn never_run_resolves_every_routes_ancestors() { + for (a, b, child) in [ + ("#[path = \"shared.rs\"]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n", "crates/x/src/shared.rs"), + ("mod shared;\n", "#[path = \"a/shared.rs\"]\nmod s;\n", "crates/x/src/a/shared.rs"), + ] { + for target in ["linux", "macos"] { + let lib = format!("#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"{target}\")]\nmod b;\n"); + let files = [("crates/x/src/lib.rs", lib.as_str()), ("crates/x/src/a.rs", a), ("crates/x/src/b.rs", b)]; + let read = |p: &str| files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(files); + let gates = module_gates(&[child.to_owned()], &read, &overrides); + let ctx = Ctx { module_cfgs: gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let expected = if target == "linux" { vec![] } else { vec![(2, "never-run")] }; + assert_eq!(hits_in(child, test, &ctx), expected, "the second route's ancestors decide whether Linux runs it"); + for (parent, line) in [ + ("crates/x/src/a.rs", if a.starts_with("#[path") { 2 } else { 1 }), + ("crates/x/src/b.rs", 2), + ("crates/x/src/lib.rs", 2), + ("crates/x/src/lib.rs", 4), + ] { + let changed = [(parent.to_owned(), Some([line].into_iter().collect()))].into_iter().collect(); + assert!(gate_changed(gates.get(child), &changed), "every route and its ancestors: {parent}:{line}"); + } + } + } + } + + #[test] + fn removed_module_routes_count_only_newly_off_tests() { + let a = "crates/x/src/a.rs"; + let child = "crates/x/src/shared.rs"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let mac = "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"; + let work_files = [("crates/x/src/lib.rs", "mod a;\nmod b;\n"), (a, ""), ("crates/x/src/b.rs", mac)]; + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let overrides = path_overrides(work_files); + let paths = [child.to_owned()]; + let gates = module_gates(&paths, &read_work, &overrides); + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let hit = lint_file(child, test, &work_ctx).into_iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + for (before, ran) in [(declaration, true), (mac, false)] { + let base_files = [("crates/x/src/lib.rs", work_files[0].1), (a, before), ("crates/x/src/b.rs", mac)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = path_overrides(base_files); + let base_gates = module_gates(&paths, &read_base, &base_overrides); + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::<Vec<_>>(); + assert!( + descendants(&[a.to_owned()], &files, &overrides, &base_overrides).contains(&child.to_owned()), + "the removed route still reaches the shared tests" + ); + for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { + let changed = [(a.to_owned(), lines)].into_iter().collect(); + assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); + let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); + assert!(parent_changed, "deletions and shifted lines still change a base route"); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert!( + route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), + "a base route parent counts even without inherited predicates" + ); + } + let changed = [("crates/x/src/lib.rs".to_owned(), Some([20].into_iter().collect()))].into_iter().collect(); + assert!( + route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed), + "an edited base ancestor counts even when its old line numbers do not match" + ); + } + } + + #[test] + fn base_path_overrides_follow_declarations_before_a_move() { + let a = "crates/x/src/a.rs"; + let b = "crates/x/src/b.rs"; + let child = "crates/x/src/shared.rs"; + let lib = "#[cfg(target_os = \"macos\")]\nmod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n"; + let declaration = "#[path = \"shared.rs\"]\nmod s;\n"; + let base_files = [("crates/x/src/lib.rs", lib), (a, declaration), (b, "")]; + let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; + let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); + let base_overrides = listed_path_overrides(&format!("before:{a}\n"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\n"), None, &read_work); + let paths = [child.to_owned()]; + let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; + let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(child, test, &work_ctx), [(2, "never-run")]); + assert_eq!(hits_in(child, test, &base_ctx), [(2, "never-run")], "the test was already off before the equally gated declaration moved"); + } + + #[test] + fn never_run_joins_two_inline_routes_from_one_file() { + let a = "#[cfg(target_os = \"macos\")]\nmod m {\n #[path = \"../shared.rs\"]\n mod s;\n}\nmod n {\n #[path = \"../shared.rs\"]\n mod s;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", a)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/src/a/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); + } + + #[test] + fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { + let files: Vec<String> = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] + .into_iter() + .map(String::from) + .collect(); + let overrides = path_overrides([ + ("src/solids/graphics.rs", "#[path = \"map_art.rs\"]\nmod art;\n"), + ("src/solids/map_art.rs", "#[path = \"tests_map_art.rs\"]\nmod tests;\n"), + ]); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new()); + assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); + } + + #[test] + fn never_run_counts_every_line_of_a_multiline_test_gate() { + let src = + "#[cfg(all(\n unix,\n target_os = \"macos\",\n))]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[3].into_iter().collect())), "an edit inside the predicate"); } #[test] @@ -5558,7 +6041,7 @@ mod tests { .into_iter() .collect(); let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); - let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read), ..ctx() }; + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/shared.rs".to_owned()], &read, &Overrides::new()), ..ctx() }; let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } From fca9f00cd474c43a26f1dcceb629d2a1f1190c1b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 07:10:54 -0800 Subject: [PATCH 42/71] Tests: check the contrast answer for a Difference square in an isolating group a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors only checked that color.contrast returned Ok. It now checks that the answer has a ratio above 1 and a background color, and that the same square in Normal mode gives a different ratio, so a contrast reading that drops the blend mode fails the test. --- crates/engine/src/tests/colorcontrast.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index fecd16ed2a..152e48a837 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -1184,7 +1184,14 @@ fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { s.execute("object.group", &json!({"ids": [back, square]})).unwrap(); s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap(); s.execute("select.set", &json!({"ids": [square]})).unwrap(); - s.execute("color.contrast", &json!({})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let isolated = ratio(&r); + assert!(isolated > 1.0, "{r}"); + assert!(r["against"].as_str().is_some_and(|h| vectorcraft_color::Color::from_hex(h).is_some()), "{r}"); + // The Difference mode is applied: in Normal mode the same square gives another answer. + s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); + let normal = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + assert!((isolated - normal).abs() > 0.1, "difference {isolated} against normal {normal}"); } /// With a fill of None, what a pick would be measured against is still read: the Color Wheel's From e1c1b04f25f1979ff5be4b2b3a182534a41d1a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 07:27:46 -0800 Subject: [PATCH 43/71] xtask: test-lint follows deleted and detached routes and decoded cfg values - A deleted file stays in the changed set and seeds the descendant walk, so a module it loaded through #[path] is checked for a lost CI route. - A parent file that no crate target loads (its mod line removed) no longer counts as an ungated route to the module it declares. - #[path] on an inline module sets the directory of the modules inside it. - git grep lists #[path] parents with -z, so non-ASCII paths are read verbatim in both trees. - cfg string values are compared decoded ("\x6cinux" is linux); raw strings stay as written. - mirror reports arithmetic on either side of the equality, and ignores comments beside lookup keys. - reads-source does not take a format! argument as the file name. - The base never-run hits are computed once per file. --- xtask/src/test_lint.rs | 253 +++++++++++++++++++++++++++++++++++------ 1 file changed, 217 insertions(+), 36 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f70326e737..0c7d793c0f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -327,7 +327,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_overrides = discover_path_overrides(root, Some(&base), &read_base); // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` // declaration can turn their tests off without a change to them. - let below: Vec<String> = descendants(&present, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); + // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. + let seeds: Vec<String> = changed.keys().cloned().collect(); + let below: Vec<String> = descendants(&seeds, &files, &overrides, &base_overrides).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec<String> = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -337,7 +339,15 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = |path: &str, src: &str, hit: &Hit| !already_off(&lint_file(path, src, &base_ctx), hit); + // The base's `never-run` hits, computed once per file on its first parent-attributed hit. + let base_off: RefCell<HashMap<String, HashSet<(String, usize)>>> = RefCell::new(HashMap::new()); + let newly_off = |path: &str, src: &str, hit: &Hit| { + let mut cache = base_off.borrow_mut(); + let off = cache.entry(path.to_owned()).or_insert_with(|| { + lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() + }); + !off.contains(&(hit.test.clone(), hit.line)) + }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); @@ -360,6 +370,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { /// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the /// test of `hit`. Tests of one name in different inline modules are told apart by their line. +#[cfg(test)] fn already_off(base: &[Hit], hit: &Hit) -> bool { base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) } @@ -570,15 +581,21 @@ fn parse_diff(diff: &str) -> BTreeMap<String, Option<BTreeSet<usize>>> { let mut current: Option<String> = None; // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. let (mut header, mut new_file) = (false, false); + let mut old: Option<String> = None; for line in diff.lines() { if line.starts_with("diff --git ") { - (header, new_file) = (true, false); + (header, new_file, old) = (true, false, None); } else if header && line.starts_with("new file mode") { new_file = true; + } else if let Some(path) = line.strip_prefix("--- ").filter(|_| header) { + old = patch_path(path).and_then(|p| p.strip_prefix("a/").map(str::to_owned)); } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } else if let Some(p) = old.take().filter(|_| path == "/dev/null") { + // A deleted file is kept, wholly changed: it may have been a route that loaded a module. + out.insert(p, None); } } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { header = false; @@ -3082,10 +3099,30 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { out } -/// The last string literal in a (whitespace-free) expression, quotes included. +/// The last string literal in a (whitespace-free) expression, quotes included. Inside a +/// `format!`-family call, an argument is not the file name, so the format string is returned +/// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; let open = arg[..close].rfind('"')?; + let b = arg.as_bytes(); + let mut depth = 0usize; + for i in (0..open).rev() { + match b[i] { + b')' => depth += 1, + b'(' if depth > 0 => depth -= 1, + b'(' => { + let head = arg[..i].strip_suffix('!').unwrap_or(""); + let name = head.rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).next().unwrap_or(""); + if matches!(name, "format" | "format_args") { + let first = arg[i + 1..].strip_prefix('"')?; + let end = first.find('"')?; + return Some(&arg[i + 1..i + 2 + end + 1]); + } + } + _ => {} + } + } Some(&arg[open..=close]) } @@ -3149,11 +3186,12 @@ fn first_arithmetic(op: &str) -> Option<usize> { } /// The whitespace-free source text of the arguments of the call an operand starts with, read from -/// the unmasked source so string literals keep their text. -fn head_args(f: &File, (from, to): (usize, usize)) -> Option<Vec<String>> { +/// `code` (the source with comments blanked and string literals kept), so a comment beside a key +/// is not part of it. +fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option<Vec<String>> { let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; let close = matching(&f.m, open)?; - Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(&f.src[a..b])).collect()) + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) } /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, @@ -3174,6 +3212,7 @@ fn key_like(arg: &str) -> bool { /// checks that two inputs agree, as a periodicity check does), and two reads at different entries /// (`at("B") == at("A") + 1`, `bounds(&s, copy) == bounds(&s, id) + dv`), which relate two entries. fn mirrors(v: &View) -> Vec<Hit> { + let code = std::cell::OnceCell::new(); v.asserts .iter() .filter(|a| a.name.ends_with("_eq")) @@ -3183,16 +3222,18 @@ fn mirrors(v: &View) -> Vec<Hit> { let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let name = head_call(l)?; // Two calls compared as they are check that two inputs agree, which is a real check. + // Arithmetic on exactly one side, in either order, derives that side from the other call. let derived = match (first_arithmetic(l), first_arithmetic(r)) { - (_, None) => false, + (None, None) => false, (Some(i), Some(j)) => l[i..] != r[j..], - (None, Some(_)) => true, + _ => true, }; let last = name.rsplit("::").next().unwrap_or(name); if l == r || !derived || head_call(r) != Some(name) || MIRROR_NEUTRAL.contains(&last) { return None; } - let (la, ra) = (head_args(v.file, lr)?, head_args(v.file, rr)?); + let code: &Vec<u8> = code.get_or_init(|| mask_parts(&String::from_utf8_lossy(v.file.src), true, false)); + let (la, ra) = (head_args(v.file, code, lr)?, head_args(v.file, code, rr)?); let mut differing = la.iter().zip(&ra).filter(|(x, y)| x != y).peekable(); let entries = la.len() == ra.len() && differing.peek().is_some() && differing.all(|(x, y)| key_like(x) && key_like(y)); (!entries).then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) @@ -3417,6 +3458,46 @@ fn windows_runs(path: &str) -> bool { path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" } +/// The value of the contents of an ordinary Rust string literal: `\x`, `\u{…}` and the single-character +/// escapes decoded. An escape it cannot read is kept as written. +fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('0') => out.push('\0'), + Some(c @ ('\\' | '"' | '\'')) => out.push(c), + Some('x') => { + let hex: String = chars.by_ref().take(2).collect(); + match u8::from_str_radix(&hex, 16) { + Ok(v) if v < 0x80 => out.push(char::from(v)), + _ => out.push_str(&format!("\\x{hex}")), + } + } + Some('u') if chars.peek() == Some(&'{') => { + let body: String = chars.by_ref().take_while(|&c| c != '}').collect(); + match u32::from_str_radix(&body[1..].replace('_', ""), 16).ok().and_then(char::from_u32) { + Some(v) => out.push(v), + None => out.push_str(&format!("\\u{body}}}")), + } + } + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + /// Whether a (whitespace-free) `cfg` predicate holds on `t`: `None` when it depends on something /// else (a feature, `debug_assertions`, an unknown key). fn cfg_value(p: &str, t: &Target) -> Option<bool> { @@ -3445,7 +3526,13 @@ fn cfg_value(p: &str, t: &Target) -> Option<bool> { return cfg_value(arg, t).map(|v| !v); } // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. - let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's + // contents are kept as written. + let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { + Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), + }); + let value = value.as_str(); match key { "test" => Some(true), "unix" => Some(t.family == "unix"), @@ -3598,7 +3685,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>, for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, at) != want.chain { + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, src.as_bytes(), at) != want.chain { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); @@ -3661,7 +3748,7 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec<String>)> { } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { - let chain = inline_mods(&m, at); + let chain = inline_mods(&m, src.as_bytes(), at); out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); } } @@ -3675,18 +3762,20 @@ type Overrides = HashMap<String, Vec<(String, Vec<String>)>>; /// Find the files carrying `#[path]` in the work tree or at `base`, then read that tree's sources. fn discover_path_overrides(root: &Path, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides { let with_path = match base { - Some(base) => git(root, &["grep", "-l", "-w", "path", base, "--", "*.rs"]), - None => git(root, &["grep", "--untracked", "-l", "-w", "path", "--", "*.rs"]), + // `-z` lists each path verbatim, NUL-terminated: without it Git quotes a non-ASCII path. + Some(base) => git(root, &["grep", "-z", "-l", "-w", "path", base, "--", "*.rs"]), + None => git(root, &["grep", "-z", "--untracked", "-l", "-w", "path", "--", "*.rs"]), } .unwrap_or_default(); listed_path_overrides(&with_path, base, read) } -/// Read paths from `git grep -l`, removing the revision prefix for a base-tree listing. +/// Read paths from `git grep -z -l` (NUL-separated), removing the revision prefix for a base-tree listing. fn listed_path_overrides(list: &str, base: Option<&str>, read: &dyn Fn(&str) -> Option<String>) -> Overrides { let prefix = base.map(|b| format!("{b}:")); let sources: Vec<(String, String)> = list - .lines() + .split('\0') + .filter(|p| !p.is_empty()) .filter_map(|p| match &prefix { Some(prefix) => p.strip_prefix(prefix), None => Some(p), @@ -3745,21 +3834,25 @@ fn join_path(base: &str, rel: &str) -> String { parts.join("/") } -/// The names of the inline `mod <name> { … }` blocks around `at` in the masked text `m`, outermost -/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. -fn inline_mods(m: &[u8], at: usize) -> Vec<String> { - m[..at] - .iter() - .enumerate() - .filter(|&(open, &c)| c == b'{' && matching(m, open).is_some_and(|close| close > at)) - .filter_map(|(open, _)| { - let head = m[..open].trim_ascii_end(); - let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - let before = head[..head.len() - name].trim_ascii_end(); - (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) - .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) - }) - .collect() +/// The directory segments of the inline `mod <name> { … }` blocks around `at` in the masked text +/// `m` (`src` unmasked), outermost first. A `mod x;` inside them loads a file under their directory +/// instead of a sibling file. A block's directory is its name, or the value of a `#[path]` on it +/// (`#[path = "platform_impl"] mod platform { mod child; }` loads `platform_impl/child.rs`). +fn inline_mods(m: &[u8], src: &[u8], at: usize) -> Vec<String> { + let mut dir = String::new(); + for open in (0..at).filter(|&open| m[open] == b'{' && matching(m, open).is_some_and(|close| close > at)) { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) { + continue; + } + let kw = before.len() - 3; + let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let seg = path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()); + dir = join_path(&dir, &seg); + } + dir.split('/').filter(|s| !s.is_empty()).map(str::to_owned).collect() } /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the @@ -3774,6 +3867,8 @@ fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option<String>, override struct Gates { preds: Vec<String>, sources: Vec<(String, Vec<usize>)>, + /// Whether a crate target loads the file through at least one route. + reached: bool, } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that @@ -3799,7 +3894,10 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Over } let by_path = overrides.get(at).map_or(&[][..], Vec::as_slice); // A crate root runs independently of any module declarations that also load it. - let Some((name, mut candidates)) = module_parent(at) else { return gates }; + let Some((name, mut candidates)) = module_parent(at) else { + gates.reached = true; + return gates; + }; let name = name.to_owned(); let file = at.rsplit_once('/').map_or(at, |(_, f)| f); let Some(mut module_dir) = (if file == "mod.rs" { @@ -3807,15 +3905,23 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Over } else { at.rsplit_once('/').map(|(d, _)| d.to_owned()) }) else { + gates.reached = true; return gates; }; let mut chain: Vec<String> = vec![]; let mut found = vec![]; + // Whether a file that could declare the module exists: when none does, the module's parent is + // unknown and the file counts as reached. + let mut parent_read = false; for _ in 0..4 { let want = Loaded { path: at, name: &name, chain: &chain }; // Every file that loads the module is another way in (a library and a binary root // can both load it): its tests are off only when every one of them leaves them out. - found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + found.extend( + candidates + .iter() + .filter_map(|c| read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))), + ); if chain.is_empty() { for (c, inline) in by_path { // A candidate was read with no inline modules; another route through the @@ -3834,8 +3940,15 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Over module_dir = up; } let mut each = vec![]; + gates.reached = found.is_empty() && !parent_read; for (parent, (mut preds, lines)) in found { let ancestors = module_gate(&parent, read, overrides, depth + 1); + // A parent that no crate target loads (a file left on disk after its `mod` line was + // removed) is not a route, so it cannot stand in for an ungated one. + if !ancestors.reached { + continue; + } + gates.reached = true; preds.extend(ancestors.preds); gates.sources.push((parent, lines)); gates.sources.extend(ancestors.sources); @@ -5537,12 +5650,16 @@ mod tests { assert_eq!(only("mirror", allowed), [], "the allow removes the hit `bad` reports"); let derived_arg = "#[test]\nfn t() {\n assert_eq!(area(grow(s, 2.0)), area(s) * 4.0);\n}\n"; assert_eq!(only("mirror", derived_arg), [(3, "mirror")], "a computed input is a quantity, not an entry"); + let swapped = "#[test]\nfn t() {\n assert_eq!(scale(p, 1.0) * 2.0, scale(p, 2.0));\n}\n"; + assert_eq!(only("mirror", swapped), [(3, "mirror")], "the arithmetic on the left side"); } #[test] fn mirrors_leave_out_reads_at_two_entries_and_shared_arithmetic() { let order = "#[test]\nfn t() {\n assert_eq!(at(\"Graphic styles\"), at(\"Swatches\") + 1);\n assert_eq!(at(front[0]), at(a) + 1);\n}\n"; assert_eq!(only("mirror", order), [], "positions of two entries in one list"); + let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", commented), [], "a comment beside a key"); let offset = "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); @@ -5961,8 +6078,8 @@ mod tests { let work_files = [("crates/x/src/lib.rs", lib), (a, ""), (b, declaration)]; let read_base = |p: &str| base_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); let read_work = |p: &str| work_files.iter().find(|(path, _)| *path == p).map(|(_, s)| (*s).to_owned()); - let base_overrides = listed_path_overrides(&format!("before:{a}\n"), Some("before"), &read_base); - let work_overrides = listed_path_overrides(&format!("{b}\n"), None, &read_work); + let base_overrides = listed_path_overrides(&format!("before:{a}\0"), Some("before"), &read_base); + let work_overrides = listed_path_overrides(&format!("{b}\0"), None, &read_work); let paths = [child.to_owned()]; let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let work_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_work, &work_overrides), ..ctx() }; @@ -5983,6 +6100,65 @@ mod tests { assert_eq!(hits_in(&shared, test, &ctx), [], "the ungated route through `n` runs it"); } + #[test] + fn a_detached_module_is_not_an_ungated_route() { + let decl = "#[path = \"shared.rs\"]\nmod s;\n"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let shared = "crates/x/src/shared.rs".to_owned(); + for (lib, off) in [("#[cfg(target_os = \"macos\")]\nmod b;\n", true), ("mod a;\n#[cfg(target_os = \"macos\")]\nmod b;\n", false)] { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", decl), ("crates/x/src/b.rs", decl)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let want: &[(usize, &str)] = if off { &[(2, "never-run")] } else { &[] }; + assert_eq!(hits_in(&shared, test, &ctx), want, "{lib}"); + } + } + + #[test] + fn a_path_on_an_inline_module_sets_its_directory() { + let lib = "#[cfg(target_os = \"macos\")]\n#[path = \"platform_impl\"]\nmod platform {\n mod child;\n}\n"; + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", lib)].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let child = "crates/x/src/platform_impl/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &Overrides::new()), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]); + } + + #[test] + fn cfg_values_compare_decoded_strings() { + let linux = &CI_TARGETS[0]; + assert_eq!(cfg_value("target_os=\"\\x6cinux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); + assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + } + + #[test] + fn path_override_listings_are_nul_separated() { + let files: HashMap<&str, &str> = + [("crates/x/src/a.rs", "#[path = \"s.rs\"]\nmod s;\n"), ("crates/x/src/caf\u{e9}.rs", "#[path = \"t.rs\"]\nmod t;\n")] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let got = listed_path_overrides("base:crates/x/src/a.rs\0base:crates/x/src/caf\u{e9}.rs\0", Some("base"), &read); + assert!(got.contains_key("crates/x/src/s.rs"), "{got:?}"); + assert!(got.contains_key("crates/x/src/t.rs"), "{got:?}"); + } + + #[test] + fn deleted_files_are_kept_as_changed() { + let diff = "diff --git a/crates/x/src/bin/tool.rs b/crates/x/src/bin/tool.rs\ndeleted file mode 100644\n--- a/crates/x/src/bin/tool.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-#[path = \"../shared.rs\"]\n-mod shared;\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/src/bin/tool.rs"), Some(&None), "{got:?}"); + let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); + let seeds: Vec<String> = got.keys().cloned().collect(); + let files = ["crates/x/src/shared.rs".to_owned()]; + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base), ["crates/x/src/shared.rs"]); + } + #[test] fn a_changed_file_reaches_the_files_its_path_loaded_modules_load() { let files: Vec<String> = ["src/solids/graphics.rs", "src/solids/map_art.rs", "src/solids/tests_map_art.rs", "src/solids/other.rs"] @@ -6053,6 +6229,11 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); + let format_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); From 66c01445d5237d3744f3d83a7054c1f829f6d2f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 07:34:06 -0800 Subject: [PATCH 44/71] Pathfinder: Divide and Live Paint report paths too complex to map When the planar map is skipped because the paths have too many pieces (SHAPE_BUILDER_MAX_MAP_EDGES, added in 7a46d5ec564), too many segments or exceed the sweep's work budget, Divide with open paths fell back to the filled areas. It replaced the selection with the uncut shapes and deleted the cutting paths without saying so. Live Paint built no faces: Make reported the paths as too degenerate to paint, and with Gap Detection a group could get its edges and no faces. pathops now has try_pathfinder_with, try_live_paint and try_live_paint_with_gaps, which return TooManyPieces in those cases without sweeping the filled areas. Divide, Live Paint Make, Merge and Gap Options use them and stop with an error that leaves the art unchanged. The caps, and the fallbacks of pathfinder_with, live_paint, live_paint_with_gaps and the Shape Builder, are unchanged. When a Gap Options preview fails after one that found gaps, the dialog no longer keeps drawing the earlier preview's gaps over the groups the failure put back. Docs: docs/mcp.md, the commands' params text and the Divide line in docs/target-app-parity.md. --- crates/engine/src/cmd/buildcmds.rs | 11 ++-- crates/engine/src/cmd/pathops.rs | 5 +- crates/pathops/src/lib.rs | 5 +- crates/pathops/src/pathfinder.rs | 41 ++++++++++--- crates/pathops/src/planar.rs | 8 +-- crates/pathops/src/planar/live_paint.rs | 60 ++++++++++++++++--- crates/pathops/src/planar/map.rs | 34 ++++++++--- crates/pathops/src/planar/shape_builder.rs | 45 ++++++++++++-- crates/pathops/src/planar/tests.rs | 30 +++++++++- crates/ui-egui/src/dialogs/live_paint_gaps.rs | 20 ++++++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 14 +++-- docs/target-app-parity.md | 4 +- 13 files changed, 227 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 426f374a5c..21618367b6 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> { "Merge", ["Object", "Live Paint"], None, - "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}", + "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step). The command stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {id, faces, edges}", has_multi_or_ids, lp_merge ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step). The command stops with an error and leaves the art unchanged when a group's paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when detect is on. → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), @@ -740,12 +740,13 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64 src_group.visible = false; children.push(Arc::new(src_group)); // Every path is an edge, open ones included; faces are the areas they enclose. + let too_many = |e: po::TooManyPieces| EngineError::Other(format!("Live Paint: {e} to paint")); let (regs, edges) = match max_gap { Some(gap) => { - let (regs, edges, _) = po::live_paint_with_gaps(&shapes, gap); + let (regs, edges, _) = po::try_live_paint_with_gaps(&shapes, gap).map_err(too_many)?; (regs, edges) } - None => po::live_paint(&shapes), + None => po::try_live_paint(&shapes).map_err(too_many)?, }; if regs.is_empty() && edges.is_empty() { return Err(EngineError::Other("Live Paint: these paths are too degenerate to paint".into())); diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 61406fdc61..2132375a44 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> { "Divide", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front). When open paths are among them, the command stops with an error and leaves the art unchanged if the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. → {ids}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Divide) ), @@ -823,7 +823,8 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> { if shapes.iter().any(|s| s.path.subpaths.iter().any(|sp| sp.anchors.iter().any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())))) { return Err(EngineError::Other("paths contain invalid coordinates".into())); } - let mut results = po::pathfinder_with(op, &shapes, options.precision); + let mut results = po::try_pathfinder_with(op, &shapes, options.precision) + .map_err(|e| EngineError::Other(format!("{label}: {e} to cut with the open paths; select fewer paths")))?; if options.remove_unpainted && matches!(op, PathfinderOp::Divide | PathfinderOp::Outline) { // Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: the pieces // of objects with no fill (or only hidden ones) go. diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 61d03ecbc1..da7960af0f 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -31,11 +31,12 @@ pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{ FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, + try_pathfinder_with, }; pub use planar::{ Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, - adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, - shape_builder_with_gap, + TooManyPieces, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, + shape_builder, shape_builder_with_gap, try_live_paint, try_live_paint_with_gaps, }; pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 3caddb4bc0..8389fd2dbb 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -109,6 +109,36 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec<Shape> { pathfinder_with(op, shapes, DEFAULT_PRECISION) } +/// [`pathfinder_with`], or [`TooManyPieces`](crate::TooManyPieces) when Divide's open paths and the +/// shapes they cut have more than [`SHAPE_BUILDER_MAX_SEGMENTS`](crate::SHAPE_BUILDER_MAX_SEGMENTS) +/// segments, or the sweep cuts them into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`](crate::SHAPE_BUILDER_MAX_MAP_EDGES) pieces, or they exceed the +/// sweep's work budget. [`pathfinder_with`] then divides only the filled areas and leaves the open +/// paths out. +pub fn try_pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Result<Vec<Shape>, crate::TooManyPieces> { + if op == PathfinderOp::Divide && crate::has_open_path(shapes) { + let precision = if precision.is_finite() && precision > 0.0 { precision } else { DEFAULT_PRECISION }; + let (faces, capped) = divide_with_open_paths(shapes, precision, false); + return if capped { Err(crate::TooManyPieces) } else { Ok(faces) }; + } + Ok(pathfinder_with(op, shapes, precision)) +} + +/// Divide with open paths as cutting edges, through the Shape Builder's bounded planar map (and, +/// with `fallback`, its filled-area fallback), and whether that map was skipped for its size. +fn divide_with_open_paths(shapes: &[Shape], precision: f64, fallback: bool) -> (Vec<Shape>, bool) { + let (arrangement, capped) = crate::planar::builder_capped(shapes, false, 0.0, precision, fallback); + let faces = arrangement + .regions + .into_iter() + .filter_map(|r| { + let key = shapes.get(r.top()?)?.key; + Some(Shape::new(r.path, FillRule::NonZero, key)) + }) + .collect(); + (faces, capped) +} + /// [`pathfinder`] at Pathfinder Options › Precision: results are refit to within `precision` /// (document units) and pieces thinner than it are dropped. A smaller value follows the inputs more /// closely. A value that isn't positive and finite is [`DEFAULT_PRECISION`]. @@ -130,14 +160,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve // Open paths are cutting edges for Divide; the filled-only operations keep their // implicit closure. Reuse Shape Builder's bounded planar map and its fallback. if op == PathfinderOp::Divide && crate::has_open_path(shapes) { - return crate::planar::builder(shapes, false, 0.0, precision) - .regions - .into_iter() - .filter_map(|r| { - let key = shapes.get(r.top()?)?.key; - Some(Shape::new(r.path, FillRule::NonZero, key)) - }) - .collect(); + return divide_with_open_paths(shapes, precision, true).0; } let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; let p = &arr.tidy; @@ -1645,6 +1668,8 @@ mod tests { assert_eq!(faces.len(), 1, "a segment past the cap falls back to filled areas"); assert_eq!(faces[0].key, 7); assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6); + // The checked Divide reports that it left the lines out. + assert_eq!(try_pathfinder_with(PathfinderOp::Divide, &inputs, DEFAULT_PRECISION), Err(crate::TooManyPieces)); } fn old_trim(shapes: &[Shape], precision: f64) -> Vec<Shape> { diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index ca473dd839..2d1eee08c9 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -37,14 +37,14 @@ pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency}; pub(crate) use graph::pin_ends; #[cfg(test)] use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done}; -pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps}; +pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps, try_live_paint, try_live_paint_with_gaps}; pub use map::interior_point; pub(crate) use map::{Map, Rest, map}; pub use shape_builder::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, - run_around, shape_builder, shape_builder_with_gap, + BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, TooManyPieces, cut_out, encloses_area, + has_open_path, run_around, shape_builder, shape_builder_with_gap, }; -pub(crate) use shape_builder::{builder, gap_inputs}; +pub(crate) use shape_builder::{builder_capped, gap_inputs}; #[cfg(test)] mod tests; diff --git a/crates/pathops/src/planar/live_paint.rs b/crates/pathops/src/planar/live_paint.rs index 1b9d5b6177..a98449dd0a 100644 --- a/crates/pathops/src/planar/live_paint.rs +++ b/crates/pathops/src/planar/live_paint.rs @@ -6,26 +6,72 @@ use super::*; /// Faces are the bounded areas the paths enclose, holes included, each with the inputs whose fill /// covers it (ascending; empty for an area only enclosed by paths). Edges are the paths split /// wherever they meet another path, keyed by the input they came from (the front-most where -/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate). +/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate), or when +/// the sweep cuts them into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed +/// the sweep's work budget ([`try_live_paint`] reports either limit). pub fn live_paint(shapes: &[Shape]) -> (Vec<Region>, Vec<Shape>) { - build(shapes, DEFAULT_PRECISION).map(|(faces, edges, _)| (faces, edges)).unwrap_or_default() + try_live_paint(shapes).unwrap_or_default() } +/// [`live_paint`], or [`TooManyPieces`] when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed the sweep's work budget. +/// No faces or edges are built in either case. +pub fn try_live_paint(shapes: &[Shape]) -> Result<(Vec<Region>, Vec<Shape>), TooManyPieces> { + Ok(build(shapes, DEFAULT_PRECISION)?.map(|(faces, edges, _)| (faces, edges)).unwrap_or_default()) +} + +/// Faces, edges and gaps, as [`live_paint_with_gaps`] gives them. +type WithGaps = (Vec<Region>, Vec<Shape>, Vec<[Point; 2]>); + +type Capped<T> = Result<T, TooManyPieces>; + +type CappedWithGaps = (Capped<Vec<Region>>, Capped<Vec<Shape>>, Vec<[Point; 2]>); + /// [`live_paint`] with Gap Detection: the faces are those of `shapes` with a line across each gap /// [`find_gaps`] finds up to `max_gap`, so paint stops at the gaps, and the edges are those of /// `shapes` alone (the lines add none). Also returns the gaps. pub fn live_paint_with_gaps(shapes: &[Shape], max_gap: f64) -> (Vec<Region>, Vec<Shape>, Vec<[Point; 2]>) { + let (faces, edges, gaps) = faces_and_edges_with_gaps(shapes, max_gap); + (faces.unwrap_or_default(), edges.unwrap_or_default(), gaps) +} + +/// [`live_paint_with_gaps`], or [`TooManyPieces`] when the sweep cuts the paths, or the paths with +/// the lines across their gaps, into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or either +/// set of paths exceeds the sweep's work budget. +pub fn try_live_paint_with_gaps(shapes: &[Shape], max_gap: f64) -> Result<WithGaps, TooManyPieces> { let gaps = find_gaps(shapes, max_gap); + let Some(closed) = with_gap_lines(shapes, &gaps) else { + let (faces, edges) = try_live_paint(shapes)?; + return Ok((faces, edges, gaps)); + }; + let (faces, _) = try_live_paint(&closed)?; + let (_, edges) = try_live_paint(shapes)?; + Ok((faces, edges, gaps)) +} + +/// The faces and the edges of [`live_paint_with_gaps`], each built on its own, and the gaps. +fn faces_and_edges_with_gaps(shapes: &[Shape], max_gap: f64) -> CappedWithGaps { + let gaps = find_gaps(shapes, max_gap); + let Some(closed) = with_gap_lines(shapes, &gaps) else { + return match try_live_paint(shapes) { + Ok((faces, edges)) => (Ok(faces), Ok(edges), gaps), + Err(e) => (Err(e), Err(e), gaps), + }; + }; + let faces = try_live_paint(&closed).map(|(faces, _)| faces); + let edges = try_live_paint(shapes).map(|(_, edges)| edges); + (faces, edges, gaps) +} + +/// `shapes` with a line across each of `gaps`, or `None` when there are none. +fn with_gap_lines(shapes: &[Shape], gaps: &[[Point; 2]]) -> Option<Vec<Shape>> { if gaps.is_empty() { - let (faces, edges) = live_paint(shapes); - return (faces, edges, gaps); + return None; } let mut closed = shapes.to_vec(); let lines = PathData::new(gaps.iter().map(|g| SubPath::polyline(g, false)).collect()); closed.push(Shape::new(lines, FillRule::NonZero, u64::MAX)); - let (faces, _) = live_paint(&closed); - let (_, edges) = live_paint(shapes); - (faces, edges, gaps) + Some(closed) } /// How many times longer than a gap the way between its two ends along the paths must be for it to diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index 051a341e1a..f2114a6ceb 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -42,11 +42,18 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> { /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> { - map_within(shapes, cover, precision, usize::MAX) + map_within(shapes, cover, precision, usize::MAX).ok().flatten() } -/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces. -pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option<Map> { +/// [`map_with`], or [`TooManyPieces`] when the sweep cuts the paths into more than `max_edges` pieces +/// or the inputs exceed the sweep's work budget. +pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Result<Option<Map>, TooManyPieces> { + let mut capped = false; + let map = map_capped(shapes, cover, precision, max_edges, &mut capped); + if capped { Err(TooManyPieces) } else { Ok(map) } +} + +fn map_capped(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize, capped: &mut bool) -> Option<Map> { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); @@ -71,10 +78,11 @@ pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edge snap_horizontals(&mut inputs.iter_mut().map(|p| &mut p.0).collect::<Vec<_>>(), eps); // Counted on the snapped geometry, which is what the sweep sees: snapping can bring boxes into contact. if !crate::budget::sweep_fits(inputs.iter().map(|p| &p.0)) { + *capped = true; return None; } let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0)); - let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?; + let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges, capped)?; let nv = points.len(); // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is @@ -193,7 +201,7 @@ pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edge Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap }) } -fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec<Point>, Vec<Edge>)> { +fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize, capped: &mut bool) -> Option<(Vec<Point>, Vec<Edge>)> { // The sweep can panic on rare near-degenerate input; that must never take the app down. let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Crossings>::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps))); @@ -202,6 +210,7 @@ fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: // the paths into, and paths that cross many times are cut into far more pieces than they have // segments. if top.segment_indices().nth(max_edges).is_some() { + *capped = true; return None; } // The planar graph: vertices are the sweep's points, edges its segments. Points closer than @@ -437,10 +446,17 @@ impl Map { /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) /// that lie under another path in front of them, whose edges are that path's: under a closed /// path's outline, or along an open path in front. -/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. -pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec<Region>, Vec<Shape>, Vec<Shape>)> { - let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?; - let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; +/// This returns [`TooManyPieces`] when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces or the inputs exceed the sweep's work budget. +pub(super) fn build(shapes: &[Shape], precision: f64) -> Result<Option<Built>, TooManyPieces> { + Ok(map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?.and_then(|m| build_from(&m, shapes, precision))) +} + +/// Faces, edges and the open paths' pieces under another path, as [`build`] gives them. +pub(super) type Built = (Vec<Region>, Vec<Shape>, Vec<Shape>); + +fn build_from(m: &Map, shapes: &[Shape], precision: f64) -> Option<Built> { + let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = m; let snap = *snap; let fills: Vec<Fill> = shapes.iter().map(Fill::new).collect(); let subpath = |cycle: &[usize]| { diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 4ddd10495a..86a2fc5f36 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -19,6 +19,20 @@ pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; /// from them still has its region. pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; +/// The paths have more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments, or the sweep cut them into +/// more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or they exceed the sweep's work budget. +/// Their planar map was not built. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TooManyPieces; + +impl std::fmt::Display for TooManyPieces { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the paths have too many segments or pieces") + } +} + +impl std::error::Error for TooManyPieces {} + /// The Shape Builder's arrangement: see [`shape_builder`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct BuilderArrangement { @@ -86,23 +100,43 @@ pub fn shape_builder_with_gap(shapes: &[Shape], edges: bool, gap: f64) -> Builde /// [`shape_builder_with_gap`] refitting its results to `precision` (Pathfinder Options › Precision). pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -> BuilderArrangement { + builder_capped(shapes, edges, gap, precision, true).0 +} + +/// [`builder`], and whether its full map was skipped because the paths have more than +/// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or the sweep cut them into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, or the inputs exceed the sweep's work budget. +/// The regions are then the filled areas', or, without `fallback`, there are none and the filled +/// areas are not swept. +pub(crate) fn builder_capped(shapes: &[Shape], edges: bool, gap: f64, precision: f64, fallback: bool) -> (BuilderArrangement, bool) { let has_open = has_open_path(shapes); let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(|sp| sp.segment_count()).sum(); + let mut capped = segments > SHAPE_BUILDER_MAX_SEGMENTS; + let mut built = |shapes: &[Shape]| match build(shapes, precision) { + Ok(b) => b.unwrap_or_default(), + Err(TooManyPieces) => { + capped = true; + Default::default() + } + }; let planar = (segments <= SHAPE_BUILDER_MAX_SEGMENTS) .then(|| { let keyed: Vec<Shape> = shapes.iter().enumerate().map(|(i, s)| Shape::new(s.path.clone(), s.rule, i as u64)).collect(); if has_open && gap.is_finite() && gap > 0.0 { - let (faces, pieces, under) = build(&gap_inputs(&keyed, gap), precision).unwrap_or_default(); + let (faces, pieces, under) = built(&gap_inputs(&keyed, gap)); // Gap targets split original outlines too, but the bridges themselves aren't art. let art = |p: &Shape| p.key < shapes.len() as u64; (faces, pieces.into_iter().filter(art).collect(), under.into_iter().filter(art).collect()) } else { - build(&keyed, precision).unwrap_or_default() + built(&keyed) } }) .filter(|(faces, pieces, _)| !faces.is_empty() || !pieces.is_empty()); let Some((faces, pieces, under)) = planar else { - return BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() }; + if capped && !fallback { + return (BuilderArrangement::default(), true); + } + return (BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() }, capped); }; let is_line = |i: u64| shapes.get(i as usize).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); let (lines, outline): (Vec<Shape>, Vec<Shape>) = pieces.into_iter().partition(|e| is_line(e.key)); @@ -114,12 +148,13 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - regions.extend(faces.into_iter().filter(|f| f.sources.is_empty())); regions }; - BuilderArrangement { + let arrangement = BuilderArrangement { regions, lines: if has_open { lines } else { Vec::new() }, edges: if edges { outline } else { Vec::new() }, lines_under: if has_open { under } else { Vec::new() }, - } + }; + (arrangement, false) } /// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 130d381bfa..99045828f6 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -623,13 +623,39 @@ fn bar_grid(n: usize) -> Vec<Shape> { fn a_map_past_its_edge_cap_is_not_built() { // 20 lines each way: each line is cut into 21 pieces, 840 in all. let s = line_grid(20); - assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some()); - assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none()); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_ok_and(|m| m.is_some())); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_err()); let bars = bar_grid(20); assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400)); assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none()); } +#[test] +fn divide_and_live_paint_report_the_edge_cap() { + // A filled square under 300 lines each way: the lines cross past the cap. + let mut s = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + s.extend(line_grid(300).into_iter().map(|l| Shape::new(l.path, l.rule, l.key + 1))); + assert_eq!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &s, DEFAULT_PRECISION), Err(TooManyPieces)); + // Without the report, Divide gives back the square alone, uncut. + assert_eq!(crate::pathfinder_with(crate::PathfinderOp::Divide, &s, DEFAULT_PRECISION).len(), 1); + assert_eq!(try_live_paint(&s), Err(TooManyPieces)); + assert_eq!(try_live_paint_with_gaps(&s, 10.0), Err(TooManyPieces)); + // Overlapping lines exceed the sweep's work budget before any pieces are cut. + let mut overlapping = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + overlapping.extend((0..1500).map(|i| line((0.0, 0.0), (1000.0, 1000.0), i + 8))); + assert_eq!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &overlapping, DEFAULT_PRECISION), Err(TooManyPieces)); + assert_eq!(crate::pathfinder_with(crate::PathfinderOp::Divide, &overlapping, DEFAULT_PRECISION).len(), 1); + assert_eq!(try_live_paint(&overlapping), Err(TooManyPieces)); + assert_eq!(try_live_paint_with_gaps(&overlapping, 10.0), Err(TooManyPieces)); + let (faces, edges) = live_paint(&overlapping); + assert!(faces.is_empty() && edges.is_empty()); + // Under the cap, both build as before. + let mut small = vec![rect(100.0, 100.0, 900.0, 900.0, 7)]; + small.extend(line_grid(20).into_iter().map(|l| Shape::new(l.path, l.rule, l.key + 1))); + assert!(crate::try_pathfinder_with(crate::PathfinderOp::Divide, &small, DEFAULT_PRECISION).is_ok_and(|f| f.len() > 1)); + assert!(try_live_paint(&small).is_ok_and(|(faces, _)| faces.len() > 1)); +} + #[test] fn shape_builder_builds_no_regions_past_its_edge_cap() { // 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index 388ded4a68..69e5e0ceed 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -198,7 +198,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(Ok(done)) => Some(done["gaps"].clone()), Some(Err(e)) => { app.status(e); - None + // The failed preview rolled the groups back, so the gaps an earlier one found are gone too. + Some(Value::Null) } None => None, }; @@ -519,6 +520,23 @@ mod tests { assert!(!drawn(&mut app), "no preview, no gap"); } + /// A preview that fails after one that found gaps leaves no gaps drawn from the earlier one. + #[test] + fn a_failed_preview_draws_no_earlier_gaps() { + let mut app = app(); + gapped_group(&mut app); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert_eq!(overlays(&app).len(), 1, "the gap is previewed"); + // A custom size past 72 pt is refused, and the preview with it fails. + set(&app, "size", json!("custom")).unwrap(); + set(&app, "custom", json!(100.0)).unwrap(); + pump_all(&mut app); + assert!(overlays(&app).is_empty(), "{:?}", overlays(&app)); + } + /// With Preview on, a Gap Preview Color with an alpha part is not previewed: the group keeps /// its own color, the gaps draw in black, OK refuses the color and Cancel rolls the preview back. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..2657f2de7b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2203,7 +2203,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)", ), ( "ui.perspectivePlane", diff --git a/docs/mcp.md b/docs/mcp.md index 9604e3da61..f75dd03691 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6074,7 +6074,9 @@ already walks Image Trace. Short agent entry points: When `livePaint.gapOptions` or `livePaint.merge` cuts an edge into pieces, each piece takes the edge's paint, with its rows fitted to its part of the edge in the same way. A face or edge given no such row has one unpainted row. Rows that do not draw stay with the stored sources, which `livePaint.release` returns unchanged. The source's object effects and the strokes' pen pressure are not carried. - Expand keeps those face fills. + Expand keeps those face fills. Make, Merge and Gap Options stop with an error and leave the art unchanged when the + paths are too many or too complex to map. This happens when the paths have more than 131,072 pieces once cut where + they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. The paths include lines across the gaps when Gap Detection is on. `livePaint.expand` keeps each face and edge that draws, with all its fill and stroke rows: it is shown, its opacity is above 0, and a fill or stroke row is shown, has paint and an opacity above 0 (a stroke also a weight above 0), whichever row is on top. A painted lower row under an unpainted top row keeps the part; a part whose only painted @@ -6098,7 +6100,9 @@ already walks Image Trace. Short agent entry points: when another merged group has it on. When Gap Detection is off in every merged group, it stays off. The Gap Options dialog (`ui.livePaintGapOptions`) takes `color` as `#rrggbb` or a layer color's name; its OK gives an error for a `color` with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. With Preview on, a - `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. + `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. When a + preview fails, the status bar shows the error, the groups go back to how they were, and the dialog stops drawing its preview of the gaps. View › Show Live Paint Gaps still draws the restored + groups' own gaps. `view.livePaintGaps` (View › Show Live Paint Gaps, or Hide Live Paint Gaps while it is on) turns the drawing of those gaps on or off. While it is on and edges show, the canvas draws the gaps of each selected Live Paint group in that group's Gap Preview Color. The reply is the new state (`true` when on). @@ -7675,8 +7679,10 @@ Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `preci whatever the options are then. Unite, Minus Front, Intersect, Exclude and Minus Back close open paths, so a straight line encloses no area and does not change the result's shape. When a selected object is or holds such a path, the reply's `warning` says so and names Object › Path › Outline Stroke. When such a path leaves the result empty (Intersect, a line -at the back in Minus Front, or a line in front in Minus Back), the error says so too. - +at the back in Minus Front, or a line in front in Minus Back), the error says so too. Divide with open paths among +the objects stops with an error and leaves the art unchanged when the paths are too many or too complex to map. +This happens when the paths Divide maps, as it prepares them from the selection, have more than 65,536 segments, have more than 131,072 pieces once cut where +they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. ```json {"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5f5f9644d5..1eb702f506 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1826,7 +1826,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow. Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests). Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`). - - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. The shared planar map keeps a segment cap (65,536 since #937, was 4,096) and its filled-area fallback; other Pathfinder operations are unchanged. + - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. Divide with open paths stops with an error and leaves the art unchanged when the paths are too many or too complex to map. This happens when the paths it maps, as it prepares them from the selection, have more than 65,536 segments (since #937, the cap was 4,096), have more than 131,072 pieces once cut where they meet, or exceed the sweep's work budget, which counts pairs of segments with overlapping bounds. Other Pathfinder operations are unchanged. - Type that Transform effects only move and copy (no scale, rotation, reflection or Random) exports as type in each place, and PDF export writes every copy as selectable, searchable text, when its characters are in solid colors without underline or strikethrough, the type object has no fills or strokes of its own, no inline graphics and no perspective, its transform does not scale or shear stroked characters, and the copies do not overlap. When the effect is on the type itself, the type can also have transparency, an opacity mask and raster effects. When the effect is on the group or layer holding the type, the type has no transparency or effects of its own and is not in a clipping path, the group or layer has no fill, stroke or Pathfinder effect of its own, and no group between them has a fill, stroke, Pathfinder or geometry effect. Type still exports as outlines when the effect stops its copies early, or when the copies would number more than 10,000 or take more than 20,000,000 bytes of document data, and so does other type under a geometry effect. - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. @@ -2106,7 +2106,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Object › Live Paint › Expand keeps the faces and edges that draw on the canvas, with all their fill and stroke rows, so the expanded paths look as the painted group did ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, a face or edge draws when it is shown, its opacity is above 0, and any of its fill or stroke rows is shown, has paint and an opacity above 0 (a stroke also needs a weight above 0), whichever row is on top: a painted lower row under an unpainted top row is kept, and a part whose only painted row is hidden is removed. Merge copies the fill and stroke rows, visibility, opacity and blending mode of each face that draws by this rule, and of each edge, to the rebuilt parts, with their gradients kept at their fit on the old outline and without the strokes' pen pressure, tilt, bearing and rotation. Evidence: `tests::build::{live_paint_expand_keeps_the_faces_and_edges_that_draw, live_paint_merge_carries_the_faces_that_draw, live_paint_merge_leaves_pen_pressure_behind, live_paint_merge_keeps_the_fit_of_carried_gradients, live_paint_merge_keeps_the_visibility_opacity_and_blending_of_carried_parts}`. `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, with its paint, opacity, visibility, weight for a stroke, and whether it draws by the rule above, beside the top fill, stroke and weight it already reported. Evidence: `tests::build::live_paint_info_lists_every_appearance_row`. - Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. + Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color, and a preview that fails puts the groups back and stops drawing the dialog's preview of the gaps. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. From 68a104ba8f2305839a3f1dd278fb3ef41152f4d5 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:00:18 +0530 Subject: [PATCH 45/71] Add item context menus to resource library panels --- crates/ui-egui/src/panels/library_panel.rs | 14 ++++++-- .../ui-egui/src/panels/library_panel/tests.rs | 36 +++++++++++++++++++ docs/ui-parity.md | 1 + 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..1cd5502a2b 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -22,7 +22,7 @@ use std::collections::HashMap; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; use craft::theme::variant::Tone; -use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; +use craft::ui::contract::{Bind, Entry, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::{Notice, NoticeAction, NoticeLayout}; use craft::ui::patterns::presets::{ @@ -675,7 +675,8 @@ fn body<K: LibraryKind>(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { let title = library_name(id, &name).to_string(); // The footer stays under the browser, which scrolls in the room left above it. let footer_out = RefCell::new(None); - let any = !selection.items.is_empty() && can_add(app, K::KIND); + let can_add = can_add(app, K::KIND); + let any = !selection.items.is_empty() && can_add; let mut shown = Panel::new(title.clone()) .collection_body() .footer(|ui, _| *footer_out.borrow_mut() = Some(footer_bar::<K>(any).show_footer(ui))) @@ -686,7 +687,9 @@ fn body<K: LibraryKind>(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { .select(SelectMode::Multi) .selection(Bind::given(selection.clone())) .empty(tl!("This library is empty.")) - .row_menu(PresetRowMenu::Off) + .row_menu(PresetRowMenu::Host) + .row_items(move |_: &LibraryKey| vec![Entry::new("ui.libraryPanel.add".to_owned(), K::ADD).enabled(can_add)]) + .host_version(u64::from(can_add)) .drags(K::drags()) .show(ui) }); @@ -696,6 +699,11 @@ fn body<K: LibraryKind>(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { for event in events { match event { PresetEvent::Selection(change) => chosen.apply(change), + PresetEvent::Menu { target, command, .. } if command == "ui.libraryPanel.add" && can_add => { + let names = + if chosen.items.contains(&target) { chosen.items.iter().map(|key| key.name.clone()).collect() } else { vec![target.name] }; + K::add(app, id, names); + } // A plain click on an item also adds and applies it; folders and modifier clicks only select. PresetEvent::Select { key, mods, .. } if !key.folder && !mods.shift && !mods.cmd => clicked = Some(key.name), _ => {} diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..58b0effd84 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -182,6 +182,42 @@ fn modifier_clicks_select_and_add_to_swatches_adds_the_selection() { assert!(selected_names(&app, "library:swatches:brights").is_empty()); } +#[test] +fn library_item_menu_adds_the_target_or_its_selection_without_applying_paint() { + for view in ["smallList", "smallThumb"] { + for target in ["Clay 1", "Clay 3"] { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": view})).unwrap(); + click(&mut app, &ctx, "Clay 1", Modifiers::COMMAND, 0.0); + click(&mut app, &ctx, "Clay 2", Modifiers::COMMAND, 1.0); + let paint = app.session.paint.fill.clone(); + let undo = undo_len(&app); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let (_, at) = control(&mut app, &ctx, &draw, target); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; + draw_frame(&mut app, &ctx, &draw, vec![Event::PointerMoved(at)]); + draw_frame(&mut app, &ctx, &draw, vec![button(true)]); + draw_frame(&mut app, &ctx, &draw, vec![button(false)]); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + let (_, row) = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::MenuItem && n.label() == Some("Add to Swatches")).unwrap(); + let bounds = row.bounds().unwrap(); + assert_eq!(undo_len(&app), undo, "opening the item menu must not edit the drawing"); + let expected = if target == "Clay 1" { vec!["Clay 1", "Clay 2"] } else { vec!["Clay 3"] }; + assert_eq!(selected_names(&app, &panel), expected); + click_at(&mut app, &ctx, &draw, Pos2::new((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5)); + for name in ["Clay 1", "Clay 2", "Clay 3"] { + assert_eq!(app.session.doc().unwrap().doc.swatch(name).is_some(), expected.contains(&name), "{view}: {target}: {name}"); + } + assert_eq!(app.session.paint.fill, paint); + } + } +} + #[test] fn adding_selected_library_items_requires_an_open_drawing() { let mut app = app(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8bb6c7b87a..775f91c648 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -526,6 +526,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | +| Swatch, Brush, Symbol and Graphic Style Library item menus | done | In list and thumbnail views, the item menu offers the same Add to action as the footer. It adds the current selection when the target is selected or the target alone otherwise. The action requires an open drawing. | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its fill or stroke (solid, gradient or pattern) and the Transparency panel setting its opacity and blend, is on canvas (#6308); `.ai` editing data keeps dynamic symbols and their instance changes when VectorCraft writes and reads it (#8747); on-canvas editing beyond fill, stroke, opacity and blend, and reading other apps' dynamic symbol records, remain | From 8ff9f4cba2ff5d99f4585f249fe8658dc7cecc83 Mon Sep 17 00:00:00 2001 From: ruchirguitar <info@jeevantirth.org> Date: Tue, 1 Dec 2026 23:33:48 +0530 Subject: [PATCH 46/71] .ai import: a visibility variable on hidden styled type binds the group that hides it Since #9228 hidden styled type whose look has its own transparency comes in as a group of the look and the type, and the group holds the hidden and locked state. A visibility variable bound to the type's XML id still bound the type, so showing it left the type hidden. The reader now records the text slot each such group wraps, and a visibility binding on that slot binds the group; text bindings stay on the type. --- crates/eps/src/import/ai/read.rs | 10 ++++--- crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ai/read/ops.rs | 6 ++--- crates/eps/src/import/native/build.rs | 17 +++++++++--- crates/eps/src/import/tests_native.rs | 32 +++++++++++++++++++++++ 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 17d9896ab9..8a29eec63e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -248,6 +248,9 @@ pub struct Structure { /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an /// id two objects have. pub xml_ids: HashMap<String, Option<NodeId>>, + /// The group of a styled text object and its look, by the text object's slot id. The group, + /// not the type in it, is hidden or locked where the text object was. + pub text_looks: HashMap<NodeId, NodeId>, /// The objects the variable library binds to its variables, by their XML ids: the importer /// binds those it keeps. pub bindings: Vec<BindingRef>, @@ -664,8 +667,9 @@ struct Reader<'a> { ruler_guides: HashMap<NodeId, (Point, Point)>, /// Legacy compound member groups, even when followed by the generic `9 () XW` marker. compound_groups: HashSet<NodeId>, - /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look. - text_looks: HashSet<NodeId>, + /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look, each + /// with the text object's slot id. + text_looks: HashMap<NodeId, NodeId>, /// Objects followed by samples of the pen (`(…) Xt n XD`), which aren't read: such an object /// whose style has a Calligraphic brush that varies with the pen keeps its drawn look (see /// [`Self::style_marker`]). @@ -911,7 +915,7 @@ impl<'a> Reader<'a> { looks: HashSet::new(), ruler_guides: HashMap::new(), compound_groups: HashSet::new(), - text_looks: HashSet::new(), + text_looks: HashMap::new(), pen_samples: HashSet::new(), group_ended: false, mesh_ended: false, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 20102b29c4..ec14b864d9 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1485,6 +1485,7 @@ impl<'a> Reader<'a> { canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, + text_looks: self.text_looks.into_iter().map(|(group, slot)| (slot, group)).collect(), bindings, bindings_skipped, warnings, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index bb5343e4f4..1b9d6aa20b 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -822,7 +822,7 @@ impl<'a> Reader<'a> { // The look is a group of paths, or one image where an effect (a blur, a shadow) rasterizes it. if !self.hidden_ids.contains(&object.id) || self.hidden_ids.contains(&look.id) != hidden - || self.text_looks.contains(&look.id) + || self.text_looks.contains_key(&look.id) || !matches!(look.kind, NodeKind::Group { clip: false, .. } | NodeKind::Image(_)) { return; @@ -978,7 +978,7 @@ impl<'a> Reader<'a> { let Some(mut look) = f.children.pop() else { return }; let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); - let (visible, locked) = (object.visible, object.locked); + let (visible, locked, slot) = (object.visible, object.locked, object.id); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); object.visible = true; object.locked = false; @@ -986,7 +986,7 @@ impl<'a> Reader<'a> { (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; group.visible = visible; group.locked = locked; - self.text_looks.insert(group.id); + self.text_looks.insert(group.id, slot); if let Some(f) = self.frames.last_mut() { f.children.push(group); } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 0637e8e079..9daa57bfd8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -350,6 +350,7 @@ pub(super) fn build_weighing( canvas_scale, symbols_own_size, xml_ids, + text_looks, bindings, bindings_skipped, warped_type, @@ -653,7 +654,7 @@ pub(super) fn build_weighing( None => unmark(&mut doc.layers, true, true, &mut vec![]), } doc.limit_depth_noting(&mut notes); - bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); + bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &text_looks, &mut notes); if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { notes.push(ai::LINKED_PREVIEWS.to_string()); } @@ -731,7 +732,9 @@ fn to_placed_documents( /// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each /// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text /// object's slot: for a visibility variable every object that took the slot's place, for a text -/// variable the one text object among them). An object is bound when it is of the variable's kind: +/// variable the one text object among them). A visibility variable binds a styled text object's +/// group with its look (`text_looks`, by slot) in place of the type: the group is what is hidden or +/// shown. An object is bound when it is of the variable's kind: /// type for a text variable, a linked image for an image variable, any object for a visibility /// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects /// on locked artboards keep their bindings. Graph variables and @@ -743,6 +746,7 @@ fn bind_variables( skipped: usize, ids: &std::collections::HashMap<String, Option<NodeId>>, filled: &std::collections::HashMap<NodeId, Filled>, + text_looks: &std::collections::HashMap<NodeId, NodeId>, notes: &mut Vec<String>, ) { let mut skipped = skipped; @@ -753,7 +757,12 @@ fn bind_variables( let mut bound = vec![]; for b in bindings { let kind = doc.variables.variable(&b.variable).map(|v| v.kind); - let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) { + let target = b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()); + let target = match kind { + Some(VariableKind::Visibility) => target.map(|id| text_looks.get(&id).copied().unwrap_or(id)), + _ => target, + }; + let targets = match (target, kind) { (Some(id), Some(kind)) => match filled.get(&id) { Some(f) if kind == VariableKind::Visibility => f.objects.clone(), Some(f) => match f.text.as_slice() { @@ -2819,7 +2828,7 @@ mod candidate_tests { bind("v_graph", "path"), ]; let mut notes = vec![]; - bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes); + bind_variables(&mut doc, &refs, 3, &ids, &filled, &Default::default(), &mut notes); let sorted = |mut v: Vec<NodeId>| { v.sort(); v diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index c5b6b61d58..d51573877a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2240,6 +2240,38 @@ fn ai_variable_bindings_bind_the_objects_they_name() { assert!(!r.warnings.iter().any(|w| w.contains("variable library")), "{:?}", r.warnings); } +/// Hidden, locked type whose style comes in as a group of its drawn look and the type (the look has +/// its own transparency) is hidden and locked on that group. A visibility variable bound to the +/// type binds the group, so showing it shows the type; a text variable still binds the type. +#[test] +fn a_visibility_variable_on_hidden_styled_type_binds_the_group_that_hides_it() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: &str| { + let uid = "/XMLUIDREF : (type_x5F_1) ;"; + let attributes = [("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name)), ("docRef", XmlValue::Raw(uid))]; + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let declared = vec![declare("v_shown", "visibility"), declare("v_text", "textcontent")]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + // The look at half opacity; the type hidden (`1 Xw`) and locked (`1 A`), with its XML id. + let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n"); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let styled = format!("{look}1 Xw\n1 A\n{own}{}1 (Unlisted) XW\n0 Xw\n0 A\n", named("type_x5F_1")); + let art = native_with_text(&(library + &layer("Art", true, &styled)), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let a = d.layers[0].children().unwrap(); + let [group] = a.as_slice() else { panic!("one group of the look and the type: {a:#?} {notes:?}") }; + assert!(matches!(group.kind, NodeKind::Group { .. }) && !group.visible && group.locked, "{group:#?}"); + let type_id = group.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id); + assert!(type_id.is_some(), "{group:#?}"); + let vars = &d.variables; + assert_eq!(vars.objects_of("v_shown"), [group.id], "the hidden group, not the type in it: {notes:?}"); + assert_eq!(vars.objects_of("v_text").first().copied(), type_id, "{notes:?}"); +} + /// An EPS whose editing data can't be used, a palette with no layers among others, comes in as its /// page with the swatches and color groups of that palette in place of the defaults. #[test] From 82cb6ef291580f4a897998b8eabf7ed14e5d0aa5 Mon Sep 17 00:00:00 2001 From: ruchirguitar <info@jeevantirth.org> Date: Tue, 1 Dec 2026 23:46:40 +0530 Subject: [PATCH 47/71] .ai import: hold the page type's word searches to their own budget #9228 let a file with many text objects whose type is made be weighed by where its pieces of type lie, up to four times the comparisons word matching may make. The page's type lying where made type draws was still searched word by word in every made text object there, and in the lines of hidden made type, so those searches could run to the larger limit. They are now counted on their own, up to MAX_PAIRS. Past it, type where made type that shows draws is taken as that type, type over hidden made type only stays on the page, and the page's type is noted as unchecked. The letters of hidden made type's lines are worked out once. --- crates/eps/src/import/native/plan.rs | 183 +++++++++++++++++++++++---- 1 file changed, 160 insertions(+), 23 deletions(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index a23e8ea324..a15c272222 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -154,8 +154,19 @@ pub(super) fn made_only( if looks && infos.len().saturating_mul(shown.len()) <= MAX_PAIRS { let spelled: Vec<String> = content.iter().map(|c| if let Content::Made(node, ..) = c { spelling(&plain_text(node)) } else { String::new() }).collect(); - let made_type = |o: &[Arc<Node>]| covered(o, &content, |_| true) && has_made_words(o, &content, &spelled); + // Past the word searches, type where made type draws is taken to be that type. + let (mut checks, mut unchecked) = (WordChecks::new(), false); + let mut made_type = |o: &[Arc<Node>]| { + covered(o, &content, |_| true) + && has_made_words(o, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }) + }; let mut spare: Vec<Vec<Arc<Node>>> = shown.iter().filter(|o| !made_type(o)).cloned().collect(); + if unchecked { + note_unchecked(warn); + } fill_look_slots(infos, &mut content, &mut spare); for c in &content { if let Content::Page(parts) = c { @@ -173,7 +184,7 @@ pub(super) fn made_only( match see_page_type(&mut content, untaken) { Some(0) => {} Some(_) => warn.push(PAGE_TYPE_LEFT_OUT.into()), - None => warn.push(PAGE_TYPE_UNCHECKED.into()), + None => note_unchecked(warn), } drop_look_slots(infos, &mut content); fill_hidden(infos, stories, &mut content, hidden); @@ -274,17 +285,64 @@ fn fill_look_slots(infos: &[SlotInfo], content: &mut [Content], spare: &mut Vec< drop_look_slots(infos, content); } +/// How many more times a word of the page's type may be looked for in a text object's type. The +/// page's type is weighed against where every text object lies up to `MAX_PLACE_PAIRS` pairs, a box +/// against a box, but each text object a piece of it lies on can be searched for each of its words: +/// those searches are held to `MAX_PAIRS` of their own. +struct WordChecks(usize); + +impl WordChecks { + fn new() -> Self { + WordChecks(MAX_PAIRS) + } + + /// One more search, if any are left. + fn spend(&mut self) -> Option<()> { + self.0 = self.0.checked_sub(1)?; + Some(()) + } + + /// Are no searches left? + fn spent(&self) -> bool { + self.0 == 0 + } +} + /// Has made type that shows and draws where the page's text object `object` lies every word of it -/// ([`spelling`], each slot's in `spelled`), in any order? -fn has_made_words(object: &[Arc<Node>], content: &[Content], spelled: &[String]) -> bool { - let Some(r) = extent(object) else { return true }; +/// ([`spelling`], each slot's in `spelled`), in any order? `None` once `checks` runs out before +/// that is known. +fn has_made_words(object: &[Arc<Node>], content: &[Content], spelled: &[String], checks: &mut WordChecks) -> Option<bool> { + let Some(r) = extent(object) else { return Some(true) }; + if checks.spent() { + return None; + } let near: Vec<&String> = content .iter() .zip(spelled) .filter(|(c, _)| matches!(c, Content::Made(_, Some(region), _) if !region.intersect(r).is_zero_area())) .map(|(_, s)| s) .collect(); - object_words(object).iter().all(|w| near.iter().any(|s| s.contains(w.as_str()))) + for w in object_words(object) { + let mut found = false; + for s in &near { + checks.spend()?; + if s.contains(w.as_str()) { + found = true; + break; + } + } + if !found { + return Some(false); + } + } + Some(true) +} + +/// Note once in `warn` that some of the page's type wasn't checked against the text objects. +fn note_unchecked(warn: &mut Vec<String>) { + if !warn.iter().any(|w| w == PAGE_TYPE_UNCHECKED) { + warn.push(PAGE_TYPE_UNCHECKED.into()); + } } /// The text slots for type that a look draws and that have nothing have no type of their own to hold @@ -438,9 +496,16 @@ pub(super) fn plan( let made_stories: std::collections::BTreeSet<u32> = infos.iter().zip(&made).filter(|(_, m)| m.is_some()).filter_map(|(i, _)| i.story).collect(); let open: Vec<bool> = infos.iter().zip(&made).map(|(i, m)| m.is_none() && i.story.is_none_or(|s| !made_stories.contains(&s))).collect(); let owner = match_page_objects(infos, &lines, &open, shown); - // Where the made type that doesn't show lies, by slot. - let hidden_at: Vec<(usize, Rect)> = - infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); + // Where the made type that doesn't show lies, and the letters of its lines (it has lines). + let hidden_at: Vec<(Rect, Vec<String>)> = infos + .iter() + .zip(&made) + .enumerate() + .filter_map(|(k, (info, m))| { + let place = m.as_ref().filter(|_| !info.shown)?.1?; + Some((place, lines.get(k)?.as_ref()?.iter().map(|(text, _)| letters(text)).collect())) + }) + .collect(); // Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box // stays that of type without a layout here: with text objects whose type isn't made stacked on // made type that has their words (the copies of an outlined heading), the page's pieces in the @@ -448,17 +513,34 @@ pub(super) fn plan( let mut content = made_content(infos, made, false); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) - let hidden_type = |object: &[Arc<Node>]| { - let Some(r) = extent(object) else { return false }; + // `None` once `checks` runs out before that is known. + let hidden_type = |object: &[Arc<Node>], checks: &mut WordChecks| -> Option<bool> { + let Some(r) = extent(object) else { return Some(false) }; let texts: Vec<Vec<String>> = object.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text())) } else { None }).collect(); - hidden_at.iter().any(|(k, place)| { - place.intersect(r).area() >= 0.5 * r.area().max(1e-9) - && lines.get(*k).and_then(Option::as_ref).is_some_and(|l| { - !texts.is_empty() - && texts.iter().all(|ws| !ws.is_empty() && ws.iter().all(|w| l.iter().any(|(text, _)| letters(text).contains(w.as_str())))) - }) - }) + if texts.is_empty() || texts.iter().any(Vec::is_empty) { + return Some(false); + } + for (place, l) in &hidden_at { + if place.intersect(r).area() < 0.5 * r.area().max(1e-9) { + continue; + } + let mut all = true; + 'words: for w in texts.iter().flatten() { + for text in l { + checks.spend()?; + if text.contains(w.as_str()) { + continue 'words; + } + } + all = false; + break; + } + if all { + return Some(true); + } + } + Some(false) }; // The letters and digits of each slot's made type that shows, in any script, in lower case. let spelled: Vec<String> = content @@ -472,6 +554,10 @@ pub(super) fn plan( }) .collect(); let mut spare: Vec<Vec<Arc<Node>>> = vec![]; + // The word searches below are held to their own budget: past it, type where made type that shows + // draws is taken to be that type (made type is there either way), and type where only made type + // that doesn't show lies stays on the page (it would not show otherwise). + let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() { Some(k) => match content.get_mut(k) { @@ -479,13 +565,28 @@ pub(super) fn plan( Some(c) => *c = Content::Page(object.clone()), None => {} }, - // What lies where made type draws, with its words, is that type as the page draws it (in - // another font, maybe, and in any script). - None if covered(object, &content, |_| true) && has_made_words(object, &content, &spelled) => {} - None if hidden_type(object) => {} - None => spare.push(object.clone()), + None => { + // What lies where made type draws, with its words, is that type as the page draws it + // (in another font, maybe, and in any script). + let theirs = covered(object, &content, |_| true) + && has_made_words(object, &content, &spelled, &mut checks).unwrap_or_else(|| { + unchecked = true; + true + }); + let hidden = !theirs + && hidden_type(object, &mut checks).unwrap_or_else(|| { + unchecked = true; + false + }); + if !theirs && !hidden { + spare.push(object.clone()); + } + } } } + if unchecked { + note_unchecked(warn); + } // The page's type that no made type takes is the spare type below. let _ = see_page_type(&mut content, shown); for (k, c) in content.iter_mut().enumerate() { @@ -600,3 +701,39 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option<Arc<Story>>], content: &mut } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{CharStyle, TextObject}; + + fn text(id: u64, s: &str) -> Node { + let style = CharStyle { size: 12.0, ..CharStyle::default() }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(100.0, 100.0), s, style)))) + } + + /// The page's type is searched for in every made text object that draws where it lies, word by + /// word: those searches stop when their budget runs out, saying they didn't finish, however many + /// made text objects lie there. A word is searched for only until a text object has it. + #[test] + fn word_searches_of_the_page_s_type_stop_when_their_budget_runs_out() { + let everywhere = Rect::new(-1e4, -1e4, 1e4, 1e4); + let slots = 50; + let content: Vec<Content> = (0..slots).map(|k| Content::Made(Box::new(text(k, "Other type")), Some(everywhere), false)).collect(); + let spelled: Vec<String> = + content.iter().map(|c| if let Content::Made(n, ..) = c { spelling(&plain_text(n)) } else { String::new() }).collect(); + // A word no made type has is searched for in each of them. + let missing = vec![Arc::new(text(1000, "Alpha beta"))]; + let one_word_everywhere = slots as usize; + let mut short = WordChecks(one_word_everywhere - 1); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut short), None, "past the budget the answer isn't known"); + assert!(short.spent()); + let mut enough = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&missing, &content, &spelled, &mut enough), Some(false)); + // Words that the first made type has are found there, without searching the others. + let present = vec![Arc::new(text(1001, "other TYPE"))]; + let mut few = WordChecks(one_word_everywhere); + assert_eq!(has_made_words(&present, &content, &spelled, &mut few), Some(true)); + assert!(one_word_everywhere - few.0 < one_word_everywhere / 2, "{} searches", one_word_everywhere - few.0); + } +} From 6f684e6da97ea173ff3612064ee81b3b37941ad0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 11:16:00 -0800 Subject: [PATCH 48/71] Path Precision Tools: Common Tangents and Smooth Bridge are one dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Common Tangents… now also does what Smooth Bridge… did (#10465). - Connect tangents joins the two tangents of each kind into one closed shape, along the chords between where they touch each path (a point's two lines make a triangle). `connect` on `addon.pathtools.commonTangents`. - With External, the dialog shows Straight and Curved. Straight keeps the tangent lines; Curved joins the circles along concave arcs, as Smooth Bridge did, with Radius, Constant Gap, Reach and Keep Originals, which take input only with Curved. `curved`, `radius`, `gap`, `reach` and `keepOriginals` on the command; options of the other mode are an error. - The Smooth Bridge… menu item is gone. `addon.pathtools.bridge` still runs for scripts and actions, opens the merged dialog with External and Curved, and is left out of the command palette and Keyboard Shortcuts. A palette search for "metaball" or "smooth bridge" finds Common Tangents. Docs: docs/mcp.md, docs/ui-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 3 +- .../engine/src/cmd/addons/pathtools/bridge.rs | 6 +- .../src/cmd/addons/pathtools/tangents.rs | 65 ++++- .../cmd/addons/pathtools/tangents/tests.rs | 107 ++++++++ crates/engine/src/cmd/params.rs | 1 + crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/addons/cutting/tests.rs | 33 --- crates/ui-egui/src/addons/dialogs.rs | 3 +- crates/ui-egui/src/addons/dialogs/tests.rs | 4 +- crates/ui-egui/src/addons/pathtools.rs | 9 +- crates/ui-egui/src/addons/pathtools/bridge.rs | 254 ------------------ .../ui-egui/src/addons/pathtools/tangents.rs | 150 +++++++++++ .../src/addons/pathtools/tangents/tests.rs | 244 +++++++++++++++++ crates/ui-egui/src/dialogs/command.rs | 6 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/palette.rs | 13 + docs/mcp.md | 29 +- docs/ui-parity.md | 2 +- 19 files changed, 613 insertions(+), 321 deletions(-) delete mode 100644 crates/ui-egui/src/addons/pathtools/bridge.rs create mode 100644 crates/ui-egui/src/addons/pathtools/tangents.rs create mode 100644 crates/ui-egui/src/addons/pathtools/tangents/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 894065391d..b04a110d6c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -182,6 +182,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. +- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8e8d96ea66..d2dc185222 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1002,7 +1002,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). -pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; +pub const ALIASES: &[(&str, &str)] = + &[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")]; /// Is `id` an [`ALIASES`] entry? pub fn is_alias(id: &str) -> bool { diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 2f56079b18..6e02292917 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec<CommandSpec> { vec![cmd!( "addon.pathtools.bridge", "Smooth Bridge", - ["Object", "Plug-ins", "Path Precision Tools"], + [], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)", has_selection, bridge )] } -fn bridge(s: &mut Session, p: &Value) -> Result<Value> { +pub(super) fn bridge(s: &mut Session, p: &Value) -> Result<Value> { let percent = given(p, "radius", Some(RADII), C)?; let gap = given(p, "gap", Some(GAPS), C)?; let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index e47c009062..372ceb6e12 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec<CommandSpec> { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}", has_selection, common_tangents )] @@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError { ) } +/// The parameters that shape a curved bridge. +const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"]; + fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = COMMON_TANGENTS; - let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + let kinds = choice(p, C, "tangents", &KINDS)?; + let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None }; + if switch_or(p, "curved", false, C)? { + if kinds.is_some_and(|k| k != "external") { + return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out")); + } + if given("centerline") { + return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`")); + } + if connect == Some(false) { + return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true")); + } + // The outline is Smooth Bridge's. + let mut bridged = serde_json::Map::new(); + for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) { + bridged.insert((*key).to_owned(), p[*key].clone()); + } + return super::bridge::bridge(s, &Value::Object(bridged)); + } + if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) { + return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it"))); + } + let kinds = kinds.unwrap_or("all"); + let connect = connect.unwrap_or(false); let centerline = switch_or(p, "centerline", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; @@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> { _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + // With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed + // shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind. + let shapes: Vec<(Vec<Point>, bool)> = if connect { + let mut out = vec![]; + for kind in [pt::TangentKind::External, pt::TangentKind::Internal] { + let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect(); + match of.as_slice() { + [l, m] => { + // A point's two lines share the point, which then closes the ring once. + let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size()); + let mut ring = vec![l.from, l.to, m.to, m.from]; + ring.dedup_by(|q, p| same(*q, *p)); + if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) { + ring.pop(); + } + out.push((ring, true)); + } + _ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))), + } + if point { + break; + } + } + out + } else { + lines.iter().map(|&(from, to)| (vec![from, to], false)).collect() + }; if lines.is_empty() && point { // Written as `EngineError::Other` so that the i18n message scan finds it. let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); @@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> { let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; let mut ids = vec![]; let mut center_id = None; - for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let center = center.map(|(from, to)| (vec![from, to], false)); + for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() { let id = d.alloc_id(); - let path = PathData::single(SubPath::polyline(&[from, to], false)); + let path = PathData::single(SubPath::polyline(&points, closed)); let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); look.apply(d, &mut n); d.insert(parent, idx + 1 + k, n)?; - if k == lines.len() { + if k == shapes.len() { center_id = Some(id); } ids.push(id); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 7ab6b32838..032ef5f377 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -354,3 +354,110 @@ fn bad_selections_and_params_are_refused() { let g = group_of(&mut s, &[b]); assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); } + +/// The one closed outline of path `id`. +fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) }; + assert!(sp.closed); + sp.clone() +} + +/// The anchors of path `id`'s one closed outline. +fn corners(s: &Session, id: NodeId) -> Vec<Point> { + outline(s, id).anchors.iter().map(|a| a.p).collect() +} + +#[test] +fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap(); + assert_eq!(steps(&s), before + 1, "one undo step"); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one shape in place of two lines"); + assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay"); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 4); + // The tangents above and below both circles, joined by each circle's vertical diameter. + for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { + assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +#[test] +fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() { + let mut s = session(); + let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0)); + let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1)); + let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap(); + let ids: Vec<NodeId> = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline"); + for &id in &ids[..2] { + let found = corners(&s, id); + assert_eq!(found.len(), 4); + let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count(); + assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}"); + } + assert_ne!(corners(&s, ids[0]), corners(&s, ids[1])); + assert_eq!(r["centerline"], json!(ids[2].0)); + + let mut s = session(); + let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0)); + let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}"); + assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0)))); +} + +#[test] +fn curved_makes_the_bridge_the_smooth_bridge_command_makes() { + let build = || { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)]; + select(&mut s, &ids); + s + }; + for (merged, old) in [ + (json!({"curved": true}), json!({})), + ( + json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}), + json!({"gap": 5, "reach": 30, "keepOriginals": true}), + ), + ] { + let (mut s, mut t) = (build(), build()); + let r = s.execute(C, &merged).unwrap(); + let q = t.execute("addon.pathtools.bridge", &old).unwrap(); + assert_eq!(r, q, "{merged}"); + let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::<Vec<_>>(); + assert_eq!(kinds(&s), kinds(&t), "{merged}"); + } +} + +#[test] +fn options_of_the_other_mode_are_refused() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + select(&mut s, &[a, b]); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + for (p, says) in [ + (json!({"connect": "yes"}), "connect"), + (json!({"curved": true, "tangents": "all"}), "external"), + (json!({"curved": true, "centerline": true}), "centerline"), + (json!({"curved": true, "connect": false}), "connected"), + (json!({"radius": 50}), "curved"), + (json!({"connect": true, "keepOriginals": true}), "curved"), + (json!({"curved": true, "radius": 50, "gap": 2}), "not both"), + (json!({"curved": true, "radius": 0}), "radius"), + ] { + assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone())); + } + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); +} diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 9b498f1ca8..0bfbe7c304 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -388,6 +388,7 @@ const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ ("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids"), ("addon.pathtools.bridge", "radius", "gap"), + ("addon.pathtools.commonTangents", "radius", "gap"), ("links.unembed", "id", "ids"), ("links.unembed", "path", "folder"), ]; diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b29f22395c..1f4ade798a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs index b177f72604..a22e907c04 100644 --- a/crates/ui-egui/src/addons/cutting/tests.rs +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -35,10 +35,6 @@ fn rect(app: &mut VectorcraftApp, x: f64, y: f64, width: f64, height: f64) -> u6 id_of(app.run("shape.rectangle", json!({"x": x, "y": y, "width": width, "height": height})).unwrap()) } -fn circle(app: &mut VectorcraftApp, cx: f64, cy: f64, r: f64) -> u64 { - id_of(app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) -} - fn select(app: &mut VectorcraftApp, ids: &[u64]) { app.run("select.set", json!({ "ids": ids })).unwrap(); } @@ -224,35 +220,6 @@ fn each_addon_dialog_opens_on_its_items_values_and_runs_its_command() { assert!(b > a, "the second object lies right of the first: {a}, {b}"); }, }, - Row { - name: "common tangents", - menu: "Path Precision Tools", - label: "Common Tangents…", - command: crate::addons::pathtools::COMMON_TANGENTS, - setup: |app| { - let (a, b) = (circle(app, 60.0, 150.0, 20.0), circle(app, 220.0, 150.0, 40.0)); - select(app, &[a, b]); - }, - opens: || json!({"tangents": "all", "centerline": false}), - set: || json!({}), - check: |app, start| { - assert_eq!(nodes(app), start.node_count() + 4, "four tangent lines"); - // Each kind the list offers is one the command takes. - for (_, kind) in crate::addons::pathtools::TANGENT_KINDS { - let params = json!({"tangents": kind}); - assert!(vectorcraft_engine::check_params(crate::addons::pathtools::COMMON_TANGENTS, ¶ms).is_ok(), "{kind}"); - } - // A circle inside another: nothing changes, and a message says why. - let ids = children(start); - let inner = circle(app, 220.0, 150.0, 10.0); - select(app, &[ids[1], inner]); - let (n, count) = (steps(app), nodes(app)); - open_item(app, "Path Precision Tools", "Common Tangents…"); - answer(app, true); - assert_eq!((steps(app), nodes(app)), (n, count)); - assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); - }, - }, Row { name: "add bounding rectangle", menu: "Path Precision Tools", diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 4abd73e430..a607911e16 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -104,7 +104,8 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul let open: fn(&mut VectorcraftApp) -> Result<Value, String> = match id { pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, - pathtools::bridge::COMMAND => pathtools::bridge::open, + pathtools::COMMON_TANGENTS => pathtools::tangents::open, + pathtools::tangents::BRIDGE => pathtools::tangents::open_connected, pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open, typetools::COMMAND => typetools::open, color::legend::COMMAND => color::legend::open, diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index c0d1c572f2..dc2372552e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -183,10 +183,10 @@ fn rows() -> Vec<Row> { }, Row { group: "Path Precision Tools", - label: "Smooth Bridge…", + label: "Common Tangents…", setup: two_circles, refused: Vec::new, - values: || vec![("keepOriginals", json!(true))], + values: || vec![("tangents", json!("external")), ("sides", json!("curved")), ("keepOriginals", json!(true))], check: |app| assert_eq!(count(app), 3, "the circles and the outline above them"), }, Row { diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 324f907615..2cb01c3e29 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Common Tangents… (the tangent lines, or circles connected along them, [`tangents`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog @@ -8,7 +8,6 @@ //! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its //! opening value: an anchor edit is one undo step that the cancel takes back. -pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -16,6 +15,7 @@ pub mod shape; pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; +pub mod tangents; use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; @@ -45,7 +45,7 @@ use crate::{VectorcraftApp, fields}; pub const ID: &str = "anchorInspector"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; -/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +/// Common Tangents' command, whose menu item opens its dialog ([`tangents`]). pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; /// The kinds of tangent Common Tangents' `tangents` picks, and their labels. pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; @@ -143,10 +143,9 @@ pub fn menu() -> Vec<Node> { cp("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), c("Divide into Dashes…", dashes::COMMAND), cp("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), - c("Smooth Bridge…", bridge::COMMAND), cp("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), c("Tangent Circle…", tangent_circle::COMMAND), - cp("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), + c("Common Tangents…", COMMON_TANGENTS), cp("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), cp("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), cp("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs deleted file mode 100644 index 5ddeee621b..0000000000 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller -//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two -//! circles selected; Keep Originals), which previews on the canvas and runs -//! `addon.pathtools.bridge` on OK. - -use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; -use craft::ui::runtime::env::UnitKind; -use serde_json::{Value, json}; - -use crate::VectorcraftApp; -use crate::addons::dialogs::{self, Spec}; -use crate::canvas::rulers::general_lengths; - -/// The command. -pub const COMMAND: &str = "addon.pathtools.bridge"; -/// The radius the command takes (%), and its default. -const RADII: std::ops::RangeInclusive<f64> = 1.0..=1000.0; -const RADIUS: f64 = 100.0; -/// The gap the command takes (pt), and the dialog's first one. -const GAPS: std::ops::RangeInclusive<f64> = 0.0..=1000.0; -const GAP: f64 = 4.0; -/// The reach the command takes (pt), and its default. -const REACHES: std::ops::RangeInclusive<f64> = 0.0..=10000.0; -const REACH: f64 = 10.0; - -/// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; - -/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. -fn params(fields: &DialogFields) -> Value { - let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); - if fields.bool("constantGap").unwrap_or(false) { - json!({ "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) - } else { - json!({ "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) - } -} - -/// Opens Smooth Bridge's dialog on the command's defaults. -pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> { - // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview - // replaces the selection with its result, with a selected group counting the objects inside it. - let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); - let fields = DialogFields::from_pairs([ - ("radius", FieldValue::Number(RADIUS)), - ("constantGap", FieldValue::Bool(false)), - ("gap", FieldValue::Number(GAP)), - ("reach", FieldValue::Number(REACH)), - ("keepOriginals", FieldValue::Bool(false)), - ("many", FieldValue::Bool(many)), - ]); - let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |fields| { - let rows = vec![ - Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)), - Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) - .length(lengths) - .bounds(Some(*GAPS.start()), Some(*GAPS.end())) - .visible_when("constantGap", FieldValue::Bool(true)), - Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) - .unit(UnitKind::Percent) - .bounds(Some(*RADII.start()), Some(*RADII.end())) - .visible_when("constantGap", FieldValue::Bool(false)), - Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) - .length(lengths) - .bounds(Some(*REACHES.start()), Some(*REACHES.end())) - .enabled_when("many", FieldValue::Bool(true)), - Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)), - ]; - ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields)) - }) -} - -/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the -/// objects inside it, at any depth; an object given twice, or with its group, counts once. -fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { - fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet<vectorcraft_doc::NodeId>) { - match &n.kind { - vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), - _ => { - out.insert(n.id); - } - } - } - let mut out = std::collections::BTreeSet::new(); - for n in ids.iter().filter_map(|&id| doc.node(id)) { - visit(n, &mut out); - } - out.len() -} - -#[cfg(test)] -mod tests { - use serde_json::{Value, json}; - use vectorcraft_engine::Session; - - use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; - use crate::{VectorcraftApp, menus}; - - fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { - app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() - } - - fn bridge_app(xs: &[f64]) -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let ids: Vec<u64> = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({"ids": ids})).unwrap(); - app - } - - fn geometry(app: &VectorcraftApp) -> Vec<vectorcraft_doc::NodeKind> { - app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() - } - - fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) { - panel.click(label); - panel.key(egui::Key::A, egui::Modifiers::COMMAND); - panel.type_text(text); - panel.key(egui::Key::Tab, egui::Modifiers::NONE); - panel.frame(); - } - - #[test] - fn real_bridge_controls_change_the_preview_and_confirmed_geometry() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); - panel.click("Keep Originals"); - type_number(&mut panel, "Radius", "150"); - let id = dialog_id(&panel.app()); - assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); - - panel.click("Constant Gap"); - type_number(&mut panel, "Gap", "6"); - let params = read(&panel.app(), id, super::params); - assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true})); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - let preview = geometry(&panel.app()); - assert_eq!(preview, geometry(&expected)); - panel.click("OK"); - panel.frame(); - assert_eq!(geometry(&panel.app()), preview); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); - assert!(!panel.app().any_dialog_open()); - } - - #[test] - fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs); - let original = geometry(&panel.app()); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(panel.enabled("Reach")); - type_number(&mut panel, "Reach", "5"); - let id = dialog_id(&panel.app()); - let params = read(&panel.app(), id, super::params); - assert_eq!(params["reach"], 5.0); - let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - panel.click("Cancel"); - panel.frame(); - assert_eq!(geometry(&panel.app()), original); - } - - #[test] - fn reach_counts_the_circles_inside_a_selected_group() { - use crate::tests::panel_harness::Panel; - - for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { - let mut app = bridge_app(xs); - let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); - let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [group]})).unwrap(); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); - panel.click("OK"); - panel.frame(); - let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); - assert_eq!(inside, 1, "the circles in the group became one shape"); - } - // A group of two circles selected together with one of them: still two circles. - let mut app = bridge_app(&[100.0, 124.0]); - let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); - let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); - } - - #[test] - fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - // Three circles 4 apart in a row and one far off. - let ids: Vec<u64> = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({ "ids": ids })).unwrap(); - menus::invoke(&mut app, super::COMMAND, Value::Null); - let dialog = dialog_id(&app); - set(&app, dialog, "constantGap", json!(true)); - // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the - // four circles the command still bridges. - frame(&mut app); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); - let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); - assert_eq!(many, Some(true), "Reach available for four circles"); - assert_eq!(params, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); - assert!(confirm(&app, dialog), "OK is on"); - frame(&mut app); - let top: Vec<u64> = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); - assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); - } - - #[test] - fn the_status_line_says_why_an_ellipse_is_refused() { - use crate::tests::panel_harness::Panel; - - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let a = circle(&mut app, 100.0, 10.0); - let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [a, oval]})).unwrap(); - let original = geometry(&app); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - let why = "an ellipse whose width and height differ is not a circle"; - assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); - panel.click("OK"); - panel.frame(); - assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); - assert_eq!(geometry(&panel.app()), original); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before, "no undo step"); - } -} diff --git a/crates/ui-egui/src/addons/pathtools/tangents.rs b/crates/ui-egui/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..1c1587a0d5 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents.rs @@ -0,0 +1,150 @@ +//! Common Tangents in the interface: one dialog for the tangent lines of two shapes and for circles joined by a smooth +//! bridge. It picks the kind of tangent, the centerline and Connect tangents (the two tangents of each kind joined into +//! one closed shape). With External, Straight keeps the tangent lines and Curved joins the circles along concave arcs +//! instead (the arcs' radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a +//! gap; the reach, unavailable with two circles selected; Keep Originals), as `addon.pathtools.bridge` does. It +//! previews on the canvas and runs `addon.pathtools.commonTangents` on OK. Smooth Bridge's command id opens the same +//! dialog with External and Curved on. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; +use crate::canvas::rulers::general_lengths; + +use super::{COMMON_TANGENTS, TANGENT_KINDS}; + +/// Smooth Bridge's command, which opens this dialog with External and Curved on. +pub const BRIDGE: &str = "addon.pathtools.bridge"; +/// The kind of tangent the dialog opens with. +const TANGENTS: &str = "all"; +/// The tangents that Curved replaces with arcs. +const EXTERNAL: &str = "external"; +/// What joins the circles with External, and its labels; the first is the default. +const SIDES: [(&str, &str); 2] = [("straight", "Straight"), ("curved", "Curved")]; +/// The radius the command takes (%), and its default. +const RADII: std::ops::RangeInclusive<f64> = 1.0..=1000.0; +const RADIUS: f64 = 100.0; +/// The gap the command takes (pt), and the dialog's first one. +const GAPS: std::ops::RangeInclusive<f64> = 0.0..=1000.0; +const GAP: f64 = 4.0; +/// The reach the command takes (pt), and its default. +const REACHES: std::ops::RangeInclusive<f64> = 0.0..=10000.0; +const REACH: f64 = 10.0; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None }; + +/// Whether the fields ask for a curved bridge: External with Curved. +fn curved(fields: &DialogFields) -> bool { + fields.text("tangents") == Some(EXTERNAL) && fields.text("sides") == Some("curved") +} + +/// The command's parameters from the dialog's fields: the tangent lines' kind, centerline and Connect tangents, or for +/// a curved bridge the radius (or with Constant Gap the gap), the reach and Keep Originals. +fn params(fields: &DialogFields) -> Value { + if !curved(fields) { + return json!({ + "tangents": fields.text("tangents").unwrap_or(TANGENTS), + "centerline": fields.bool("centerline").unwrap_or(false), + "connect": fields.bool("connect").unwrap_or(false), + }); + } + let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); + if fields.bool("constantGap").unwrap_or(false) { + json!({ "tangents": EXTERNAL, "curved": true, "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) + } else { + json!({ "tangents": EXTERNAL, "curved": true, "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) + } +} + +/// Opens Common Tangents' dialog for the tangent lines. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> { + open_with(app, false) +} + +/// Opens Common Tangents' dialog with External and Curved on, for Smooth Bridge's command. +pub(crate) fn open_connected(app: &mut VectorcraftApp) -> Result<Value, String> { + open_with(app, true) +} + +fn open_with(app: &mut VectorcraftApp, bridge: bool) -> Result<Value, String> { + // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview + // replaces the selection with its result, with a selected group counting the objects inside it. + let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); + let fields = DialogFields::from_pairs([ + ("tangents", FieldValue::from(if bridge { EXTERNAL } else { TANGENTS })), + ("centerline", FieldValue::Bool(false)), + ("connect", FieldValue::Bool(bridge)), + ("sides", FieldValue::from(if bridge { "curved" } else { "straight" })), + ("constantGap", FieldValue::Bool(false)), + ("radius", FieldValue::Number(RADIUS)), + ("gap", FieldValue::Number(GAP)), + ("reach", FieldValue::Number(REACH)), + ("keepOriginals", FieldValue::Bool(false)), + ("many", FieldValue::Bool(many)), + ]); + let lengths = general_lengths(app); + dialogs::open(app, &SPEC, fields, move |fields| { + let kinds = TANGENT_KINDS.iter().map(|(label, id)| ((*id).to_owned(), tl!(label).into())).collect(); + let sides = SIDES.iter().map(|(id, label)| ((*id).to_owned(), tl!(label).into())).collect(); + let curved = || ["curved"]; + // Picking another kind of tangent goes back to Straight, so Curved only holds while External does. + let rows = vec![ + Param::new("tangents", tl!("Tangents:"), ParamKind::choice(kinds, Some(TANGENTS.to_owned()))).resets(["sides"]), + Param::new("centerline", tl!("Centerline"), ParamKind::bool(false)).enabled_when("sides", "straight"), + // A curved bridge is always connected. + Param::new("connect", tl!("Connect tangents"), ParamKind::bool(false)).enabled_when("sides", "straight").disabled_value(true), + Param::new("sides", tl!("Sides"), ParamKind::radio(sides, Some(SIDES[0].0.to_owned()))).visible_when("tangents", EXTERNAL), + Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) + .length(lengths) + .bounds(Some(*GAPS.start()), Some(*GAPS.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [true]) + .enabled_when_in("sides", curved()), + Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) + .unit(UnitKind::Percent) + .bounds(Some(*RADII.start()), Some(*RADII.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [false]) + .enabled_when_in("sides", curved()), + Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) + .length(lengths) + .bounds(Some(*REACHES.start()), Some(*REACHES.end())) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()) + .and_enabled_when_in("many", [true]), + Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + ]; + ParamDialog::new(COMMON_TANGENTS, tl!("Common Tangents"), rows).previews(true).values(Bind::bound(fields)) + }) +} + +/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the +/// objects inside it, at any depth; an object given twice, or with its group, counts once. +fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { + fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet<vectorcraft_doc::NodeId>) { + match &n.kind { + vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => { + out.insert(n.id); + } + } + } + let mut out = std::collections::BTreeSet::new(); + for n in ids.iter().filter_map(|&id| doc.node(id)) { + visit(n, &mut out); + } + out.len() +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/pathtools/tangents/tests.rs b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..c3f1b84163 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs @@ -0,0 +1,244 @@ +//! Common Tangents' dialog: the tangent lines, Connect tangents, External's Straight or Curved bridge, Smooth +//! Bridge's command opening it curved, the reach's availability, Cancel and the refusals on the status line. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{BRIDGE, COMMON_TANGENTS}; +use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; +use crate::tests::panel_harness::Panel; +use crate::{VectorcraftApp, menus}; + +fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() +} + +fn circles_app(xs: &[f64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec<u64> = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + app +} + +fn geometry(app: &VectorcraftApp) -> Vec<vectorcraft_doc::NodeKind> { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn type_number(panel: &mut Panel, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +/// The geometry the command makes on `xs`'s circles with `params`. +fn expected(xs: &[f64], params: &Value) -> Vec<vectorcraft_doc::NodeKind> { + let mut app = circles_app(xs); + app.session.execute(COMMON_TANGENTS, params).unwrap(); + geometry(&app) +} + +#[test] +fn the_menu_item_adds_the_tangent_lines_and_only_their_options_take_input() { + let xs = [100.0, 200.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + assert!(panel.enabled("Centerline") && panel.enabled("Tangents") && panel.enabled("Connect tangents")); + assert!(!panel.shows("Radius") && !panel.shows("Straight"), "the bridge's options wait for External"); + panel.click("Centerline"); + panel.frame(); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "all", "centerline": true, "connect": false})); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms), "the preview"); + assert_eq!(geometry(&panel.app()).len(), 2 + 5, "four tangents and the centerline beside the circles"); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn external_shows_straight_or_curved_and_curved_takes_the_bridge_options() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + let id = dialog_id(&panel.app()); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + assert!(panel.shows("Straight") && panel.shows("Radius"), "External shows the bridge's options"); + assert!(!panel.enabled("Radius") && !panel.enabled("Keep Originals"), "Straight keeps them unavailable"); + panel.click("Connect tangents"); + panel.frame(); + let straight = read(&panel.app(), id, super::params); + assert_eq!(straight, json!({"tangents": "external", "centerline": false, "connect": true})); + assert_eq!(geometry(&panel.app()), expected(&xs, &straight)); + assert_eq!(geometry(&panel.app()).len(), 3, "the circles and one closed shape"); + + panel.click("Curved"); + panel.frame(); + assert!(panel.enabled("Radius") && panel.enabled("Keep Originals") && !panel.enabled("Centerline")); + let curved = read(&panel.app(), id, super::params); + assert_eq!(curved, json!({"tangents": "external", "curved": true, "radius": 100.0, "reach": 10.0, "keepOriginals": false})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, &curved)); + assert_eq!(preview.len(), 1, "the bridge replaces the circles"); + + // Another kind of tangent goes back to Straight and the lines' options. + set(&panel.app(), id, "tangents", json!("internal")); + panel.frame(); + assert!(panel.enabled("Centerline") && !panel.shows("Curved")); + assert_eq!(read(&panel.app(), id, super::params)["tangents"], "internal"); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + panel.click("Curved"); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1, "one undo step"); +} + +#[test] +fn the_bridge_command_opens_the_dialog_connected_and_its_controls_reach_the_command() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Radius"), "External and Curved are on"); + assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); + panel.click("Keep Originals"); + type_number(&mut panel, "Radius", "150"); + let id = dialog_id(&panel.app()); + assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); + let mut old = circles_app(&xs); + old.session.execute(BRIDGE, &json!({"radius": 150, "keepOriginals": true})).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&old), "the same outline Smooth Bridge makes"); + assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); + + panel.click("Constant Gap"); + type_number(&mut panel, "Gap", "6"); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 6.0, "reach": 10.0, "keepOriginals": true})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, ¶ms)); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn a_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { + let xs = [100.0, 124.0, 148.0, 300.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let original = geometry(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Reach")); + type_number(&mut panel, "Reach", "5"); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params["reach"], 5.0); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms)); + panel.click("Cancel"); + panel.frame(); + assert_eq!(geometry(&panel.app()), original); +} + +#[test] +fn reach_counts_the_circles_inside_a_selected_group() { + for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { + let mut app = circles_app(xs); + let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); + panel.click("OK"); + panel.frame(); + let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); + assert_eq!(inside, 1, "the circles in the group became one shape"); + } + // A group of two circles selected together with one of them: still two circles. + let mut app = circles_app(&[100.0, 124.0]); + let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); +} + +#[test] +fn constant_gap_bridges_many_circles_within_reach() { + let mut app = circles_app(&[100.0, 124.0, 148.0, 300.0]); + let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + menus::invoke(&mut app, BRIDGE, Value::Null); + let dialog = dialog_id(&app); + set(&app, dialog, "constantGap", json!(true)); + // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the four + // circles the command still bridges. + frame(&mut app); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); + let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); + assert_eq!(many, Some(true), "Reach available for four circles"); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); + assert!(confirm(&app, dialog), "OK is on"); + frame(&mut app); + let top: Vec<u64> = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); +} + +#[test] +fn the_status_line_says_why_a_selection_is_refused() { + // Connected: an ellipse is not a circle. + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 10.0); + let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, oval]})).unwrap(); + let original = geometry(&app); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + let why = "an ellipse whose width and height differ is not a circle"; + assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); + panel.click("OK"); + panel.frame(); + assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); + assert_eq!(geometry(&panel.app()), original); + assert_eq!(steps(&panel.app()), before, "no undo step"); + + // The lines: a circle inside another has none, and the warning says so. + let mut app = circles_app(&[150.0]); + let outer = app.run("shape.ellipse", json!({"x": 100, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let inner = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + app.run("select.set", json!({"ids": [inner, outer]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + let count = geometry(&panel.app()).len(); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before); + assert_eq!(geometry(&panel.app()).len(), count); + assert!(panel.app().ui.status.contains("inside the other"), "{}", panel.app().ui.status); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6d8741d342..6be16732f6 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -349,8 +349,7 @@ fn heading_in(lang: crate::i18n::Lang, label: &str) -> String { /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and /// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path -/// Precision Tools › Common Tangents and the bounding shapes (Add Bounding Rectangle… and Add -/// Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) +/// Precision Tools' bounding shapes (Add Bounding Rectangle… and Add Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) fn previews(command: &str, opening: &Map<String, Value>) -> bool { match command { "object.repeat.options" => opening.contains_key("gridType"), @@ -361,7 +360,6 @@ fn previews(command: &str, opening: &Map<String, Value>) -> bool { | crate::addons::cutting::WEED | crate::addons::cutting::BANNER | crate::addons::cutting::NEST - | crate::addons::pathtools::COMMON_TANGENTS | crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => true, _ => false, @@ -465,7 +463,6 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], - crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], @@ -484,7 +481,6 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), - (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), ("object.rasterize", "antiAlias") => Some(RASTERIZE_ANTI_ALIAS), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 671ebcec8f..0be68e7a2b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 017486e7ad..98f7ac967d 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -2786,4 +2786,17 @@ mod tests { } } } + + /// Smooth Bridge is part of Common Tangents (#10465): the palette lists Common Tangents once, a search for + /// "metaball" or "smooth bridge" finds it, and Smooth Bridge's own command is no result. + #[test] + fn a_search_for_metaball_finds_common_tangents_and_not_smooth_bridge() { + let app = app_on(Session::new()); + let built = built_for(&app); + assert!(built.entries.iter().all(|e| !e.ids().iter().any(|id| id == "addon.pathtools.bridge")), "Smooth Bridge is no result"); + for query in ["metaball", "smooth bridge"] { + let found = ranked(&built, query); + assert_eq!(found.first().map(String::as_str), Some(crate::addons::pathtools::COMMON_TANGENTS), "{query}: {found:?}"); + } + } } diff --git a/docs/mcp.md b/docs/mcp.md index 5a32fe1e32..ad7c424552 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16981,7 +16981,7 @@ Commands: - `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection, with a group other than a clipping group giving the objects inside it at any depth, which must all be circles; paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › - Plug-ins › Path Precision Tools › Smooth Bridge…). Two circles become one closed outline that goes around each circle + Plug-ins › Path Precision Tools › Common Tangents… with External and Curved). Two circles become one closed outline that goes around each circle on its side away from the other and along two concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every anchor is smooth. `radius` is the arcs' radius as a percentage of the smaller circle's radius (1 to 1,000, 100 by default): a larger radius makes a wider, gentler bridge. `gap` (0 to 1,000 @@ -17011,10 +17011,11 @@ Commands: other stays as it is. The shapes and the circles left as they are are selected. It is an error when any pair within reach has one circle inside the other, when no pair within reach can be bridged (suggesting a larger radius or gap only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`: - the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog - (`ui.menuDialog {command}`, key `addon.pathtools.bridge`) with Constant Gap (a Gap field in place of the Radius field in - percent), Reach (unavailable when the selection, a selected group's objects counted, holds two objects), Keep Originals - and Preview. + the shapes and the circles left as they are, with `id` as well for two circles. Opening `addon.pathtools.bridge` + from the menu dialog (`ui.menuDialog {command}`) opens Common Tangents' dialog (key + `addon.pathtools.commonTangents`) with External and Curved on, described under + `addon.pathtools.commonTangents`. No menu item runs `addon.pathtools.bridge`, and the command palette and Keyboard + Shortcuts leave it out; scripts and actions still run it. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` @@ -17115,7 +17116,7 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). -- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed +- `addon.pathtools.commonTangents {tangents?, centerline?, connect?, curved?, radius?, gap?, reach?, keepOriginals?, ids?}` adds the common tangent lines of two convex closed paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or @@ -17140,9 +17141,19 @@ Commands: runs from the point to the path's center. Two points are refused with "select two closed paths". The lines are stroked with the current stroke color and weight (black when the stroke is None), have no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of the kind asked for, - nothing changes, and the result's `warning` says why. Common Tangents… opens a dialog (Tangents, Centerline) with - Preview; with a point selected, every Tangents choice gives the same lines. → `{ids, external, internal, - centerline, warning?}` (`centerline`: the centerline's id, or null). + nothing changes, and the result's `warning` says why. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). With `connect: true` the two tangents of each kind become one closed + path instead of two lines, joined by the chords between where they touch each path (two internal tangents make a + crossed shape, and a point's two lines make a triangle); a kind with one tangent stays a line, and the centerline + stays a line. With `curved: true` it joins the selected circles into one outline along concave arcs instead, as + `addon.pathtools.bridge` does, taking that command's `radius` or `gap`, `reach`, `keepOriginals` and `ids`, and + the result is that command's. `tangents` other than `external`, `centerline` and `connect: false` with `curved` are + an error, and so are `radius`, `gap`, `reach` and `keepOriginals` without it. Common Tangents… opens a dialog with + Tangents, Centerline and Connect tangents; with External it also shows Straight and Curved (Straight by default) and + the bridge's options: Constant Gap (a Gap field in place of the Radius field in percent), Reach (unavailable when the + selection, a selected group's objects counted, holds two objects) and Keep Originals, which take input only with + Curved. With Curved, Centerline is unavailable and Connect tangents shows on. Choosing another kind of tangent goes + back to Straight. With a point selected, every Tangents choice gives the same lines. - `addon.pathtools.boundingRectangle {each?, offset?}` draws a live rectangle on the geometric bounding box of the selected objects, strokes and effects left out (Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle…, #6966). `addon.pathtools.boundingCircle {each?, offset?}` draws the smallest live circle that holds the outlines of diff --git a/docs/ui-parity.md b/docs/ui-parity.md index fa75b28fb4..2f94f51885 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -592,7 +592,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Common Tangents… with External and Curved (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/tangents.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | From 186e6db9bae18223917fe6cbb24dccbaaa68f864 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 13:34:08 -0800 Subject: [PATCH 49/71] xtask: test-lint reads renames, cfg_attr paths, casts and arm bindings - changed mode diffs with --no-renames, so an exact rename lists the old path as deleted and the new path as added, and both seed the route walk. - census reads a cast of the loop binding (k as usize) as the entry, and no longer reads a field or path segment named like it (config.k, m::k). - reads-source takes the file name from the final .join(...) component; a final component that is not a literal is an unknown file. - mirror keeps whitespace inside string literals when it compares lookup keys, so "A B" and "AB" are different entries. - fixture-only resolves a name bound by a match arm's pattern to that arm, not to an outer let; a guard still reads the outer binding. - never-run follows #[cfg_attr(<cond>, path = "...")] overrides: the selected path is loaded where the condition holds, and the default path elsewhere. - never-run treats tests/<dir>/mod.rs as loaded by the test targets beside it, like a crate root. - exact-pixel no longer reports two rects compared by their difference (a.width() - b.width()). --- xtask/src/test_lint.rs | 266 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 245 insertions(+), 21 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 0c7d793c0f..0e3baa802e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -343,9 +343,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_off: RefCell<HashMap<String, HashSet<(String, usize)>>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache.entry(path.to_owned()).or_insert_with(|| { - lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect() - }); + let off = cache + .entry(path.to_owned()) + .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); !off.contains(&(hit.test.clone(), hit.line)) }; let (mut counted, mut older) = (vec![], 0usize); @@ -560,6 +560,8 @@ fn changed_lines(root: &Path, base: &str) -> Result<BTreeMap<String, Option<BTre "--inter-hunk-context=0", "--no-color", "--no-ext-diff", + // A rename shows as a deletion and an addition, so both paths count as changed. + "--no-renames", "--src-prefix=a/", "--dst-prefix=b/", base, @@ -1782,13 +1784,20 @@ fn round_trip_call(op: &str, var: &str) -> bool { }) } -/// Whether `s` contains the identifier `var` as a whole word. +/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or +/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). fn reads_ident(s: &str, var: &str) -> bool { + const PRIMITIVES: &[&str] = + &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); + let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); - !(at > 0 && is_ident(b[at - 1])) && !b.get(end).copied().is_some_and(is_ident) + let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); + let path = at > 1 && &b[at - 2..at] == b"::"; + let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); + !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) }) } @@ -3084,8 +3093,12 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { let rs = match word { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, - // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. A final + // component that is not a literal (`.join(name)`) names an unknown file. + b"read_to_string" => { + let last = arg.rfind(".join(").and_then(|at| matching(arg.as_bytes(), at + 5).map(|close| &arg[at + 6..close])); + last_literal(last.unwrap_or(&arg)).is_some_and(|l| l.ends_with(".rs\"")) + } _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3191,7 +3204,35 @@ fn first_arithmetic(op: &str) -> Option<usize> { fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option<Vec<String>> { let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?; let close = matching(&f.m, open)?; - Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) + Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm_outside_literals(code.get(a..b).unwrap_or(&f.src[a..b]))).collect()) +} + +/// [`norm`] that keeps whitespace inside string literals: `"A B"` and `"AB"` are different keys. +fn norm_outside_literals(b: &[u8]) -> String { + let mut out = Vec::with_capacity(b.len()); + let mut in_str = false; + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + out.push(c); + if c == b'\\' { + if let Some(&n) = b.get(i + 1) { + out.push(n); + i += 1; + } + } else if c == b'"' { + in_str = false; + } + } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { + in_str = true; + out.push(c); + } else if !c.is_ascii_whitespace() { + out.push(c); + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() } /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, @@ -3321,13 +3362,67 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(Strin let pattern = norm(pattern.as_bytes()); open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() }); - match (loop_at, &found) { + // A match arm's pattern binds its names inside that arm only. + let inner = loop_at.max(arm_binding(body, name, before)); + match (inner, &found) { (Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init), (Some(_), _) => Some(None), (None, _) => found.map(|(init, _)| init), } } +/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body +/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not. +fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> { + let mut found = None; + for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") { + // The pattern runs back to the `{` or `,` that opens the arm. + let mut depth = 0usize; + let mut start = arrow; + while start > 0 { + match body[start - 1] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth == 0 => break, + b'(' | b'[' | b'{' => depth -= 1, + b',' if depth == 0 => break, + _ => {} + } + start -= 1; + } + // A guard (`Some(x) if x == n`) reads names; it does not bind them. + let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); + let pattern = norm(&body[start..guard]); + if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + continue; + } + // The arm's body: a block, or an expression up to the `,` or brace that ends the arm. + let from = skip_ws(body, arrow + 2); + let end = match body.get(from) { + Some(b'{') => matching(body, from), + _ => { + let mut depth = 0usize; + (from..body.len()).find(|&i| match body[i] { + b'(' | b'[' | b'{' => { + depth += 1; + false + } + b')' | b']' | b'}' if depth == 0 => true, + b')' | b']' | b'}' => { + depth -= 1; + false + } + b',' => depth == 0, + _ => false, + }) + } + }; + if end.is_some_and(|end| before < end) { + found = Some(arrow); + } + } + found +} + /// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it. fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> { let mut found = None; @@ -3644,13 +3739,20 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { /// The module name a file declares and the files that may declare it with `mod <name>;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under +/// `examples` beside a crate's `src`, or a file directly in `src/bin`), and for a `mod.rs` one +/// directory below those, which their roots load (`tests/common/mod.rs`). A `tests` directory under /// `src` holds modules, not test targets. fn module_parent(path: &str) -> Option<(&str, Vec<String>)> { let (dir, file) = path.rsplit_once('/')?; - let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); - let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin"); - if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { + let is_root_dir = |dir: &str| { + let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src")); + ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin") + }; + let root_dir = is_root_dir(dir); + // `tests/common/mod.rs` is loaded by the target roots beside it (`tests/smoke.rs` with + // `mod common;`), which are not listed here, so it counts as reached like a root. + let beside_roots = file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up)); + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") || beside_roots { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; @@ -3689,22 +3791,38 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>, continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let loads = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path, + // A `cfg_attr` override loads its path where its condition holds, and the default (or a + // plain `#[path]`) elsewhere. + let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); + let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; + let fallback = match path_attr(&m, src.as_bytes(), item, at) { + Some(rel) => overrides_here(&rel), None => { &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - if !loads { - continue; - } + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let route = match (fallback, selected.is_empty(), conditional.is_empty()) { + (true, _, true) => None, + (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(","))), + (true, false, false) => { + let others: Vec<&str> = conditional.iter().filter(|(_, rel)| !overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + (!others.is_empty()).then(|| format!("not(any({}))", others.join(","))) + } + (false, true, _) => continue, + (false, false, _) => Some(format!("any({})", selected.join(","))), + }; // Inner attributes cover the file, and [`cfgs_over`] reads them. let attrs: Vec<CfgAttr> = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect(); at_lines.push(lines.of(at)); // Every line of a multiline attribute counts: an edit inside its predicate changes it. at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end))); let mut preds: Vec<String> = attrs.into_iter().map(|a| a.pred).collect(); + if let Some(route) = route { + preds.push(route); + at_lines.extend(lines.of(skip_ws(&m, item))..=lines.of(at)); + } for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) { preds.push(p); at_lines.extend(lines.of(a)..=lines.of(e)); @@ -3747,7 +3865,9 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec<String>)> { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) { + let rels = + path_attr(&m, src.as_bytes(), item, at).into_iter().chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, r)| r)); + for rel in rels { let chain = inline_mods(&m, src.as_bytes(), at); out.push((override_path(dir, file, mod_rs, &chain, &rel), chain)); } @@ -3819,6 +3939,31 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> { }) } +/// The `#[cfg_attr(<condition>, path = "…")]` overrides in `m[from..to]`, each as its condition and +/// path. +fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { + let mut out = vec![]; + for at in words(m, b"cfg_attr", from, to) { + if !m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) { + continue; + } + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let text = pred_text(&src[open + 1..close]); + let cuts = top_level_at(&text, ","); + let Some(&first) = cuts.first() else { continue }; + let mut start = first + 1; + for cut in cuts[1..].iter().copied().chain([text.len()]) { + let arg = text.get(start..cut).unwrap_or(""); + if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) { + out.push((text[..first].to_owned(), rel.to_owned())); + } + start = cut + 1; + } + } + out +} + /// `rel` joined to the directory `base`, with `.` and `..` resolved. fn join_path(base: &str, rel: &str) -> String { let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect(); @@ -4028,8 +4173,14 @@ fn names_rect(op: &str) -> bool { if b.get(after) == Some(&b'(') { after = matching(b, after).map_or(b.len(), |c| c + 1); } - let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The rect and its parts make up the whole operand: `a.width() - b.width()` compares two + // rects, not one with a number. + let mut rest = &op[after..]; + while let Some(r) = RECT_PARTS.iter().chain(&[".x", ".y"]).find_map(|p| rest.strip_prefix(p)) { + rest = r; + } + let lead = op[..i].trim_start_matches(['&', '*', '(']); + if rest.trim_start_matches(')').is_empty() && !lead.contains(['+', '-', '*', '/', '%', ',']) { return true; } } @@ -4112,6 +4263,13 @@ mod tests { let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>(); let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n"; assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry"); + let cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(k as usize), k);\n }\n}\n"; + assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); + let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; + assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let field = + "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; + assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; assert_eq!(census(derived), [(2, "census")]); let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n"; @@ -5660,6 +5818,10 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; + assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; + assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); let offset = "#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n"; assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other"); @@ -5678,6 +5840,10 @@ mod tests { assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", arm), [], "a match arm binds its own n"); + let outer = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) if m == n => assert_eq!(n, 0),\n _ => assert_eq!(n, 0),\n }\n}\n"; + assert_eq!(only("fixture-only", outer), [(2, "fixture-only")], "a guard reads the outer n"); let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; @@ -5921,6 +6087,18 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets"); assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src"); + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/common/mod.rs\"]\nmod common;\n"), + ("crates/x/tests/smoke.rs", "mod common;\n"), + ("crates/x/tests/common/mod.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/tests/common/mod.rs".to_owned(); + let shared_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(&shared, test, &shared_ctx), [], "a test target beside it loads the shared module on every target"); } #[test] @@ -5955,6 +6133,45 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn never_run_follows_a_path_selected_by_cfg_attr() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"live.rs\")]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n"), + ("crates/x/src/live.rs", ""), + ("crates/x/src/platform.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let live = "crates/x/src/live.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..ctx() }; + assert_eq!(hits_in(&live, test, &ctx), [], "Linux loads live.rs through the cfg_attr path"); + let platform = "crates/x/src/platform.rs".to_owned(); + let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides); + assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere"); + } + + #[test] + fn changed_lines_lists_both_paths_of_an_exact_rename() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n"; + std::fs::write(root.join("crates/x/src/bin/tool.rs"), src).unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::create_dir_all(root.join("crates/x/src/disabled")).unwrap(); + std::fs::rename(root.join("crates/x/src/bin/tool.rs"), root.join("crates/x/src/disabled/tool.rs")).unwrap(); + git(&root, &["add", "-A"]).unwrap(); + let changed = changed_lines(&root, &base).unwrap(); + assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted"); + assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn never_run_joins_inline_and_override_routes() { for (lib, child) in [ @@ -6208,6 +6425,8 @@ mod tests { assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(left_rect.width() - right_rect.width(), 0.0);"), [], "two rects compared by their difference"); + assert_eq!(px("assert_eq!(left_rect.width(), 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); @@ -6229,6 +6448,11 @@ mod tests { assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file"); + let unknown = "#[test]\nfn t() {\n let name = \"data.json\";\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(name)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", unknown), [], "a final component that is not a literal"); + let joined = + "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read"); let format_rs = From 4ce98e803263933233d22e6b55ca97e3fc19e2f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 13:45:26 -0800 Subject: [PATCH 50/71] MCP: regenerate the UI catalog for the Gap Options preview text The params text of ui.livePaintGapOptions in crates/ui-egui/src/menus/ui_commands.rs gained the failed-preview sentence, but crates/mcp/src/ui_catalog.rs was not regenerated, so `cargo xtask ui-commands --check` failed in CI. This is the output of `cargo xtask ui-commands`. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f2ef87651c..baffcb9634 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2202,7 +2202,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black; a preview that fails shows its error in the status bar, puts the groups back as they were and stops drawing the dialog's preview of the gaps (View › Show Live Paint Gaps still draws the restored groups' own gaps)", ), ( "ui.perspectivePlane", From 7183a91544853c274f1b94a1cff760881c931885 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 13:52:58 -0800 Subject: [PATCH 51/71] Preferences: Reset All Warning Dialogs turns dismissed warnings back on General gets a Reset All Warning Dialogs button after the Show External Script Warning row. It turns every warning that a Don't Show Again box turned off back on in the Preferences window, and OK or Apply saves it. The button is dimmed while every warning is on, so a click then changes nothing. The warnings with a Don't Show Again box are listed in one place (`WARNING_DIALOGS`), so a later dialog with the box joins the reset by adding its preference there. --- crates/ui-egui/src/prefs_dialog/model.rs | 29 ++++++++++++- crates/ui-egui/src/prefs_dialog/tests.rs | 53 ++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 3a951fb6cb..847610adb4 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -8,7 +8,7 @@ use std::sync::{Mutex, PoisonError}; use craft::host::{PickKind, PickRequest}; use craft::theme::Rgba; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::form::{SliderField, SliderFieldLayout}; use craft::ui::layout_components::Row; use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PathSetting, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec}; @@ -26,6 +26,21 @@ use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt}; /// The pixel size every point-stored length field of this port uses. const PIXELS_PER_INCH: f64 = 72.0; +/// The preferences that a dialog's Don't Show Again box turns off, one per dialog; General › Reset All Warning +/// Dialogs turns each of them back on. The button follows the last one's row. +pub(super) const WARNING_DIALOGS: &[&str] = &["showExternalScriptWarning"]; + +/// The row key of the Reset All Warning Dialogs button. +const RESET_WARNINGS_KEY: &str = "resetWarningDialogs"; + +/// Turns the warning preferences `keys` back on in the draft, as Reset All Warning Dialogs does; OK or Apply writes +/// them. +pub(super) fn reset_warning_dialogs(w: &mut PrefsWindow, keys: &[&str]) { + for key in keys { + w.set_row(key, &json!(true)); + } +} + /// The model of the open window: the app, and the window taken out of it for the pass. pub(super) struct Live<'a> { pub(super) app: &'a mut VectorcraftApp, @@ -264,6 +279,10 @@ impl Live<'_> { let english = "Script File Access revoke read write file folder"; groups.add(sp.section, self.row(script_access::KEY, tl!("Script File Access"), english, RowKind::CustomRows)); } + if WARNING_DIALOGS.last() == Some(&sp.key) { + let english = "Reset All Warning Dialogs don't show again"; + groups.add(sp.section, self.row(RESET_WARNINGS_KEY, "", english, RowKind::Custom)); + } } if cat == PREF_CATEGORIES[0] { let tools = self.row("prefsFile", "", "export import reset preferences", RowKind::Custom); @@ -370,6 +389,14 @@ impl PreferencesModel for Live<'_> { script_access::show(self.app, &mut self.w.script_access, ui); false } + RESET_WARNINGS_KEY => { + let turned_off: Vec<&str> = WARNING_DIALOGS.iter().copied().filter(|k| !self.bool_of(k)).collect(); + if Button::new(tl!("Reset All Warning Dialogs")).enabled(!turned_off.is_empty()).show(ui).clicked() { + reset_warning_dialogs(self.w, &turned_off); + return true; + } + false + } "prefsFile" => { let (mut export, mut import, mut reset) = (false, false, false); let web = crate::io::is_web(self.app); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index fc61192b84..5b15a52f69 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1536,3 +1536,56 @@ fn script_file_access_revoke_names_the_whole_path() { } let _ = std::fs::remove_dir_all(store.parent().unwrap()); } + +/// One frame of the Reset All Warning Dialogs row in the window's context with `events` → the texts it drew, each +/// with its place. +fn reset_warnings_frame(a: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> { + let ctx = a.ui_ctx.clone().expect("a window context"); + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), events, ..Default::default() }; + let out = crate::testing::part_frame(a, &ctx, raw, |a, ui| { + let Some(mut w) = a.prefs.take() else { return }; + let _ = model::Live { app: &mut *a, w: &mut w }.custom_row(ui, "resetWarningDialogs"); + a.prefs = Some(w); + }); + crate::tests_removeanchors::shapes_text(&crate::tests_labels::flat_painted_shapes(&out.shapes)) +} + +/// Clicks Reset All Warning Dialogs with the pointer. +fn click_reset_warnings(a: &mut VectorcraftApp) { + reset_warnings_frame(a, vec![]); + let texts = reset_warnings_frame(a, vec![]); + let label = "Reset All Warning Dialogs"; + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + reset_warnings_frame(a, vec![egui::Event::PointerMoved(at)]); + reset_warnings_frame(a, vec![press(true)]); + reset_warnings_frame(a, vec![press(false)]); +} + +/// General shows Reset All Warning Dialogs beside the warning a Don't Show Again box turned off. With the warning +/// off, the button turns it back on in the window and OK saves it; with every warning on, the button is dimmed and +/// a click leaves the row untouched. +#[test] +fn reset_all_warning_dialogs_turns_a_dismissed_warning_back_on() { + let mut a = app(); + a.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).unwrap(); + open(&mut a, Some("General")); + let rows: Vec<(String, String)> = with_pages(&mut a, |pages| { + let general = pages.iter().find(|p| p.id == "General").expect("a General page"); + general.groups.iter().flat_map(|g| g.rows.iter().map(|r| (g.title.unwrap_or_default().to_string(), r.key.to_string()))).collect() + }); + let at = |key: &str| rows.iter().position(|(_, k)| k == key).unwrap_or_else(|| panic!("no {key} in {rows:?}")); + let (warning, reset) = (at("showExternalScriptWarning"), at("resetWarningDialogs")); + assert!(warning < reset && rows[warning].0 == rows[reset].0, "the button follows the warning's row in its section: {rows:?}"); + + click_reset_warnings(&mut a); + assert_eq!(field(&a, "showExternalScriptWarning"), json!(true), "the window shows the warning on"); + assert!(!a.session.prefs.show_external_script_warning, "nothing is saved before OK"); + confirm(&mut a).unwrap(); + assert!(a.session.prefs.show_external_script_warning, "OK saves the warning on"); + + open(&mut a, Some("General")); + click_reset_warnings(&mut a); + assert!(!a.prefs.as_ref().unwrap().touched.contains("showExternalScriptWarning"), "a dimmed button changes nothing"); +} From 827f4fc87ebfe78ddbe31024ee3f63d24676539c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 14:10:14 -0800 Subject: [PATCH 52/71] Tests: make isolation change the contrast answer for the grouped Difference square The white square behind the Difference square was opaque, so the art behind the group never reached the blend and the test gave the same answer with isolation off. That square is now 50 % opaque. The test checks that the isolating group gives one answer and that the same group without isolation reports that the art behind the selection is not one color. --- crates/engine/src/tests/colorcontrast.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 152e48a837..2ac70f800d 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -1160,9 +1160,10 @@ fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() { assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}"); } -/// A Difference square over a white square in a 50 % group that isolates its blending, over the -/// edge between black and white art: the square blends only with the white inside the group, so +/// A Difference square over a 50 % white square in a 50 % group that isolates its blending, over +/// the edge between black and white art: the square blends only with the white inside the group, so /// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer. +/// Without isolation the blend also reaches that art, and there is no one answer. #[test] fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { let mut s = session(); @@ -1177,17 +1178,29 @@ fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + // Translucent, so that a blend that is not isolated also reaches the art behind the group. + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap()); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); - s.execute("object.group", &json!({"ids": [back, square]})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [back, square]})).unwrap()); s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap(); s.execute("select.set", &json!({"ids": [square]})).unwrap(); let r = s.execute("color.contrast", &json!({})).unwrap(); let isolated = ratio(&r); assert!(isolated > 1.0, "{r}"); assert!(r["against"].as_str().is_some_and(|h| vectorcraft_color::Color::from_hex(h).is_some()), "{r}"); + // Without isolation the square also blends with the black and white art, so there is no one answer. + let set_isolate = |s: &mut Session, on: bool| { + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": on})).unwrap(); + s.execute("select.set", &json!({"ids": [square]})).unwrap(); + }; + set_isolate(&mut s, false); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("is not one color where it is read"), "{e}"); + set_isolate(&mut s, true); // The Difference mode is applied: in Normal mode the same square gives another answer. s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); let normal = ratio(&s.execute("color.contrast", &json!({})).unwrap()); From 5d494db4d99dd45ab9657fc9a5a1168c2cd8173f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 14:16:38 -0800 Subject: [PATCH 53/71] Tests: Connect tangents' external shape does not cross itself The test checked only which corners the shape has, so corners joined in the wrong order passed. It now also checks the shape's area. --- crates/engine/src/cmd/addons/pathtools/tangents/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 032ef5f377..1653089520 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -385,6 +385,9 @@ fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_o for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); } + // In order around the band, not crossing itself: the area is the 100 by 40 rectangle's. + let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::<f64>() / 2.0; + assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().doc.node_count(), count); } From 7e7826c6e9c05cfc221d5cfa1a489b81747e79ed Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 14:25:21 -0800 Subject: [PATCH 54/71] Gradient: the stop popover's CMYK sliders keep the stop's own values The Color tab of the gradient stop popover gave its Color panel only the stop's sRGB, so every frame the rows worked their values out again from that sRGB. On a CMYK stop, typing a value or dragging one slider rewrote the other channels: typing Cyan 40 on C10 M20 Y30 K5 gave M17.3 Y24.7 K0. The popover now passes the stop's values in its own model, as the Color panel does, so a typed value stays as typed and a drag changes only the dragged channel. The new test types Cyan, sets Magenta and drags Yellow on a CMYK stop and checks the exact channel values after each edit. --- crates/ui-egui/src/dialogs/gradient_stop.rs | 94 +++++++++++++++++++-- 1 file changed, 86 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 5b2ee66107..e9e05185b5 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -17,7 +17,8 @@ use std::sync::Arc; use craft::behavior::IconId; use craft::color_ui::ui::{ - ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, SwatchPalette, + ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, PickedColor, + SwatchPalette, }; use craft::theme::Srgba; use craft::theme::variant::Tone; @@ -43,6 +44,7 @@ use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; use crate::VectorcraftApp; +use crate::panels::color::model_values; use crate::panels::gradient::{edit_point, edits_points, set_stops, set_stops_keeping_models, shown_points}; use crate::panels::{Live, active_paint, c32}; @@ -470,6 +472,9 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi filed.panels.push( ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2]) .layout(ColorPanelLayout::FillStroke) + // The rows show and edit the stop's own values (CMYK %, working RGB), not values + // derived again from its sRGB on every frame. + .edited(Some(PickedColor::in_model(feed.current, model_values(&feed.color)))) .shown(feed.shown.clone()) .show(ui), ); @@ -575,13 +580,11 @@ fn place(app: &VectorcraftApp, ctx: &egui::Context, anchor: Anchor) -> Pos2 { } } -/// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. -fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { - let Some(dialogs) = app.dialogs() else { return }; - let Some(anchor) = dialogs.with(|host| host.get_by_id::<GradientStopPopover>(id).map(|popover| popover.anchor)) else { return }; +/// `target`'s values, the document's swatches and what the Color panel shows, for the popover's body. +fn feed(app: &VectorcraftApp, target: &Target) -> Feed { let shown = crate::panels::color::shown(app, &crate::panels::color::target_now(app)); let swatches = swatch_colors(app); - let feed = Feed { + Feed { point: matches!(target, Target::Point(..)), color: target.color(), current: Srgba::from(c32(&target.color())), @@ -590,7 +593,14 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar tiles: swatches.iter().map(|(name, c)| (Label::from(name.clone()), Srgba::from(c32(c)))).collect(), swatches, shown, - }; + } +} + +/// Pushes `target`'s values, the swatches, what the Color panel shows and the place into the open popover `id`. +fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Target) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(anchor) = dialogs.with(|host| host.get_by_id::<GradientStopPopover>(id).map(|popover| popover.anchor)) else { return }; + let feed = feed(app, target); let at = place(app, ctx, anchor); dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) { @@ -776,7 +786,14 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { #[cfg(test)] mod tests { use craft::behavior::{EditEvent, GestureId, Mixed}; - use craft::color_ui::ui::{PanelTarget, PickedColor}; + use std::cell::RefCell; + use std::rc::Rc; + + use craft::color_ui::ui::PanelTarget; + use craft::ui::runtime::access::Role; + use craft::ui::testing::Fixture; + use craft::ui::testing::focus::AccessActionKind; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; @@ -1203,4 +1220,65 @@ mod tests { host::pump(&mut app, &ctx); assert!(!is_open(&app)); } + + /// The popover's body over `app`'s selected stop in `mode`, drawn headless; each frame's Color panel output is + /// applied to the stop as `pump` applies it. + fn panel_body(app: Rc<RefCell<VectorcraftApp>>, mode: ColorPanelMode) -> Fixture { + let mut tab = Tab::Color; + let mut panel = ColorPanelState::default(); + panel.mode = mode; + app.borrow_mut().ui.color_panel.mode = mode; + let mut fx = Fixture::new(move |ui| { + let mut app = app.borrow_mut(); + let Some(target) = selected(&app) else { return }; + let feed = feed(&app, &target); + let mut filed = Filed::default(); + body(ui, &feed, &mut tab, &mut panel, &mut filed); + for output in &filed.panels { + crate::panels::color::apply_output(&mut app, output); + } + }); + fx.room(vec2(320.0, 640.0)).settle(); + fx + } + + fn stop_cmyk(app: &VectorcraftApp) -> [f32; 4] { + let Color::Cmyk { c, m, y, k } = stops(app)[1].color else { panic!("a CMYK stop: {:?}", stops(app)[1].color) }; + [c, m, y, k] + } + + /// A CMYK value typed or set on one row of the popover changes only that channel: the others keep their + /// exact values instead of being worked out again from the stop's RGB. + #[test] + fn a_cmyk_stop_keeps_its_other_channels_when_one_is_typed_or_dragged() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let stops_json = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": {"c": 10, "m": 20, "y": 30, "k": 5}}, {"offset": 1, "color": "#000000"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops_json, "start": [100, 150], "end": [200, 150]}, "keepModel": true})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); + assert!(close(stop_cmyk(&app), [0.10, 0.20, 0.30, 0.05]), "{:?}", stop_cmyk(&app)); + let app = Rc::new(RefCell::new(app)); + let mut fx = panel_body(app.clone(), ColorPanelMode::CmykSliders); + let row = |fx: &Fixture, name: &str| { + fx.by_role(Role::SLIDER).into_iter().find(|t| fx.tree().name_of(t.node) == Some(name)).unwrap_or_else(|| panic!("the {name} slider")) + }; + // Typed: the Cyan field gets 40. + let field = fx.by_role(Role::SPIN_BUTTON).into_iter().find(|t| fx.tree().name_of(t.node) == Some("Cyan")).expect("the Cyan field"); + fx.click(&field).key(Key::A, Modifiers::COMMAND).type_text("40").key(Key::Enter, Modifiers::NONE).settle(); + let typed = stop_cmyk(&app.borrow()); + assert!(close(typed, [0.40, 0.20, 0.30, 0.05]), "typed Cyan: {typed:?}"); + // Set as a screen reader sets it: the Magenta slider goes to 60. + let magenta = row(&fx, "Magenta"); + fx.access(AccessActionKind::SetValue(60.0), &magenta).idle(2); + let set = stop_cmyk(&app.borrow()); + assert!(close(set, [0.40, 0.60, 0.30, 0.05]), "Magenta set to 60: {set:?}"); + // Dragged with the pointer: the Yellow slider's thumb goes from a tenth to most of the way across. + let yellow = row(&fx, "Yellow"); + let along = |f: f32| egui::pos2(yellow.rect.left() + f * yellow.rect.width(), yellow.rect.center().y); + fx.drag_at(along(0.1), along(0.8) - along(0.1)).idle(2); + let [c, m, y, k] = stop_cmyk(&app.borrow()); + assert!(close([c, m, k, 0.0], [0.40, 0.60, 0.05, 0.0]), "dragged Yellow kept the other channels: {:?}", [c, m, y, k]); + assert!(y > 0.5, "the drag moved Yellow: {y}"); + } } From 86a5efd04c0ae4ddee3c50342c7b7c5732a98f91 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 14:38:27 -0800 Subject: [PATCH 55/71] Export for Screens: Include Bleed files of an artboard hold the bleed once With Include Bleed, a .vectorcraft, .ai or EPS row wrote the artboard already grown by the document's bleed and kept the document's bleed as well. Opened again, the file had the bleed outside the grown artboard, so a PDF with the document's bleed came out with it twice: a 3 mm bleed made a 6 mm one. These files now hold the grown artboard with a bleed of 0. PDF rows and Full Document files are unchanged. The params text and docs/mcp.md say so. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/screens.rs | 23 ++++++++---- crates/engine/src/cmd/fileio/tests_screens.rs | 36 +++++++++++++++++++ docs/mcp.md | 3 +- 4 files changed, 55 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a48ac3e85b..99a916a453 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it", has_doc, screens::export_for_screens ), diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 0fb1cc0860..4cc3cad433 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1131,23 +1131,29 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { /// The document the file of `item` that row `r` writes carries when it carries one /// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a -/// native, `.ai` or EPS row ([`board_document`]), else the item's document. -fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. `grown`: Include Bleed +/// grew the artboards by the document's bleed. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>, grown: bool) -> std::borrow::Cow<'a, Document> { match (&item.every_artboard, r.format.id, single) { (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), - _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item, grown)), _ => std::borrow::Cow::Borrowed(&*item.doc), } } /// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with -/// its background color and the art on it, as Save's separateArtboards writes it (#3868). -fn board_document(item: &Item) -> Document { +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). When +/// Include Bleed grew the artboard (`grown`), the artboard already holds the bleed, so the document +/// is written with a bleed of 0: opened again, its pages are not grown by the bleed a second time. +fn board_document(item: &Item, grown: bool) -> Document { let mut d = single_artboard(&item.doc, item.region, &item.name); if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { a.color = from.color; } super::save::keep_art_on(&mut d, item.region); + if grown && item.every_artboard.is_none() { + d.setup.bleed = [0.0; 4]; + } d } @@ -1209,7 +1215,7 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value> let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); let board = item.artboard.filter(|_| !all && r.whole_document()); if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) - && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref(), ungrown.is_some()), base) { return Err(bad(C, super::access::IMAGE_OUTSIDE)); } @@ -1402,7 +1408,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(pdf_doc.unwrap_or(all), "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); + let d = board_docs + .entry((Arc::as_ptr(&item.doc) as usize, b)) + .or_insert_with(|| Arc::new(board_document(item, pdf_doc.is_some()))) + .clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 74356b6f31..93c4d7e6b1 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -1512,3 +1512,39 @@ fn each_piece_writes_its_own_native_document() { assert!(name.contains(&board), "{name} holds the artboard {board}"); } } + +/// With Include Bleed, a native, `.ai` or EPS file of an artboard holds the artboard grown by the +/// bleed, and no bleed of its own: opened again, a PDF with the document's bleed has the same page +/// as the export's own PDF row, not one grown by the bleed twice. A Full Document file keeps the +/// document's bleed around its art's bounds, which Include Bleed doesn't grow. +#[test] +fn include_bleed_native_files_hold_the_bleed_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("document.setup", &json!({"bleed": 9})).unwrap(); + let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]})); + let [(_, pdf)] = &files(&r)[..] else { panic!("one PDF: {r}") }; + let [(media, bleed, ..)] = page_sizes(pdf)[..] else { panic!("one page") }; + let reopened = |name: &str, bytes: &[u8]| -> (Session, Vec<PageSizes>) { + let mut t = Session::new(); + t.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + let r = t.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}, "preserveEditing": false})).unwrap(); + let pages = page_sizes(&b64(&r)); + (t, pages) + }; + for format in ["vectorcraft", "ai", "eps"] { + let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": format}]})); + let [(name, bytes)] = &files(&r)[..] else { panic!("one {format} file: {r}") }; + let (t, pages) = reopened(name, bytes); + let [(m, b, trim, _)] = pages[..] else { panic!("{format}: one page") }; + assert_eq!((m, b), (media, bleed), "{format}: the page of the PDF row"); + assert_eq!(trim, bleed, "{format}: the artboard holds the bleed"); + assert_eq!(t.doc().unwrap().doc.setup.bleed, [0.0; 4], "{format}: no second bleed"); + } + // Full Document: the art's bounds, with the document's bleed around them. + let r = export(&mut s, json!({"includeBleed": true, "fullDocument": true, "formats": [{"format": "vectorcraft"}]})); + let [(name, bytes)] = &files(&r)[..] else { panic!("one file: {r}") }; + let (t, _) = reopened(name, bytes); + assert_eq!(t.doc().unwrap().doc.setup.bleed, [9.0; 4]); +} diff --git a/docs/mcp.md b/docs/mcp.md index 43d1223804..bd8053d754 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12068,7 +12068,8 @@ height (`"100h"`) or a resolution (`"72ppi"`); raster rows name their files `@2x otherwise. `fullDocument` writes one file per row instead (a PDF of every artboard, other formats the bounds of all art), `includeBleed` grows each artboard by the document's bleed (a PDF row's page keeps the artboard as its TrimBox and puts the row's `bleed` around it once: the row's own values, zero included, else the document's bleed -when the row sets none and its PDF preset gives none or a bleed of 0), `includeArtboardFill: false` (Include Artboard +when the row sets none and its PDF preset gives none or a bleed of 0; a native, `.ai` or EPS file of an artboard +holds the grown artboard with a bleed of 0, so the bleed is not added again when the file is opened), `includeArtboardFill: false` (Include Artboard Fill unchecked) leaves the artboards' background colors out of the files, `pdfs: "single"` (Export PDFs As › Single file) writes the artboards a PDF row exports as the pages of one PDF named after the document (it is refused with `assets`, `layers` or `selection: "each"`, whose files each hold one item's art), `subfolders` puts each From a0f7ba0ed1cc90293e0e554adb58dbf5e391b4ee Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 15:40:44 -0800 Subject: [PATCH 56/71] Tests: exempt the macOS-only Quick Pen touchpad test from never-run main's CI fails at test-lint since #8808 merged: keys_held_during_a_touchpad_gesture_count_until_it_ends is compiled only on macOS, which no CI test leg runs. egui reports a touchpad gesture's phases only on macOS; on Windows and Linux it reads a touchpad's Ctrl+scroll as a pinch, so the test cannot run there. The allow comment names that reason. --- crates/ui-egui/src/tests/quickpenwheel.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/tests/quickpenwheel.rs b/crates/ui-egui/src/tests/quickpenwheel.rs index 98c3a82e13..a6a88d648d 100644 --- a/crates/ui-egui/src/tests/quickpenwheel.rs +++ b/crates/ui-egui/src/tests/quickpenwheel.rs @@ -292,6 +292,7 @@ fn a_touchpad_steps_once_per_wheel_line() { /// Ctrl+scroll as a pinch, which carries no phases. #[cfg(target_os = "macos")] #[test] +// test-lint: allow never-run egui reports touchpad gesture phases only on macOS fn keys_held_during_a_touchpad_gesture_count_until_it_ends() { let mut app = app(); on_canvas(&mut app, |rig| { From 4bbb277a86bf9c086167590f598f3e1b554ddaec Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 16:14:39 -0800 Subject: [PATCH 57/71] Properties: a drag does not measure the panel's sections on each move The Properties panel measured all of its sections before showing them whenever the document's revision changed. A Selection tool drag changes the revision on every pointer move, so each frame of the drag ran the whole panel twice. On a blank document with one rectangle, a drag frame ran 396 components where a hover frame ran 170. The revision is now kept apart from the selection, tool and isolation key. While a canvas drag or a scrubbed field is in progress, a new revision alone does not measure the sections; the edit is measured once when the drag ends. A drag frame now runs 168 components and each frame still takes one pass. --- crates/ui-egui/src/panels/properties.rs | 18 +++++-- crates/ui-egui/src/panels/properties/tests.rs | 51 +++++++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 3ee8c24ce5..6194f28085 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -29,6 +29,8 @@ pub struct PropertiesUi { quick_actions: Option<(u64, Vec<QuickAction>)>, /// The [`content_key`] the sections were last shown for. content: Option<u64>, + /// The document (uid, revision) the sections were last shown for. + revision: Option<(u64, u64)>, } /// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -66,7 +68,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let guides = super::transform::selected_guides(app); let header = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some()); let content = content_key(app); - let changed = app.ui.properties_panel.content.replace(content) != Some(content); + let revision = app.session.active().map(|st| (st.uid, st.revision)); + let content_changed = app.ui.properties_panel.content.replace(content) != Some(content); + let edited = std::mem::replace(&mut app.ui.properties_panel.revision, revision) != revision; + // A drag on the canvas, or a scrubbed field, moves the revision on every pointer move without changing which + // sections show: the sections are measured again for an edit once the drag ends, not on each move. + let dragging = app.session.active().is_some_and(|st| st.interaction.is_some() || st.undo_group.is_some()); + let changed = content_changed || (edited && !dragging); let mut sections = |ui: &mut Ui, _: &mut BodyCx<'_>| { // The reference panel's labels end in a colon beside fields that keep their own width. Stack::new().fill_width().labels(LabelScheme::Form).show(ui, |ui, _| { @@ -87,19 +95,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut panel = Panel::new(header).titled().strength(HeaderStrength::Quiet).labels(LabelScheme::Inspector).pad(Pad::None); panel = panel.id_salt(egui::IdSalt::new(key)); if changed { + #[cfg(test)] + SECTION_MEASURES.with(|n| n.set(n.get() + 1)); let _ = panel.measure_in(ui, Proposal::Size(ui.available_size()), &mut sections); } panel.show(ui, sections); } -/// What the sections show: the document and its revision, the selection, the tool and isolation mode. +/// What the sections show besides the document's revision: the document, the selection, the tool and isolation mode. fn content_key(app: &VectorcraftApp) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.tool_id().hash(&mut h); if let Some(st) = app.session.active() { let selection = &st.selection; - (st.uid, st.revision, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h); + (st.uid, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h); for (id, anchors) in &selection.anchors { (id, anchors.len()).hash(&mut h); } @@ -223,6 +233,8 @@ fn quick_actions_key(app: &VectorcraftApp) -> u64 { thread_local! { /// How many times this thread has listed the Quick Actions. pub(crate) static QUICK_ACTION_LISTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// How many times this thread has measured the panel's sections before showing them. + pub(crate) static SECTION_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } /// [`quick_actions`], listed again only when [`quick_actions_key`] changed. diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 97c9f1e9bb..c46bcbf6e4 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -190,6 +190,57 @@ fn a_selection_change_draws_the_window_in_one_pass() { } } +/// Dragging the selected object with the Selection tool, with the Properties panel docked, does not measure the +/// panel's sections on each pointer move, and each frame of the drag takes one pass. The release measures them once +/// for the moved object, and so does an edit made without a drag. +#[test] +fn a_drag_does_not_measure_the_sections_on_each_move() { + let measures = || SECTION_MEASURES.with(std::cell::Cell::get); + let mut app = new_app(); + let a = rect(&mut app, 100.0, 100.0, 80.0, 80.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + app.select_tool("selection"); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + // One frame with `events` → (the passes it took, the section measures it made). + let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + events, + ..Default::default() + }; + let (pass, measured) = (ctx.cumulative_pass_nr(), measures()); + let _ = crate::testing::app_frame(app, &ctx, raw); + (ctx.cumulative_pass_nr() - pass, measures() - measured) + }; + for _ in 0..4 { + frame(&mut app, vec![]); + } + let x = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.selection.objects.first().and_then(|id| st.doc.node(*id)).and_then(|n| n.geometric_bounds()).unwrap().x0 + }; + let start_x = x(&app); + let start = app.canvas_view().unwrap().to_screen(craft::behavior::kurbo::Point::new(140.0, 140.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&mut app, vec![Event::PointerMoved(start)]); + assert_eq!(frame(&mut app, vec![button(start, true)]), (1, 0), "the press"); + let mut at = start; + for step in 1..=6 { + at = start + egui::vec2(8.0 * step as f32, 5.0 * step as f32); + assert_eq!(frame(&mut app, vec![Event::PointerMoved(at)]), (1, 0), "move {step} of the drag"); + } + assert_eq!(frame(&mut app, vec![button(at, false)]), (1, 1), "the release measures the moved object's sections once"); + assert!(x(&app) > start_x, "the drag moved the object"); + assert_eq!(frame(&mut app, vec![]).1, 0, "a settled frame"); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(frame(&mut app, vec![]).1, 1, "an edit without a drag measures the sections"); +} + /// Start Global Edit in Quick Actions starts it on the one selected path, the button then reads /// Stop Global Edit, and Escape stops it. Selected type has no Start Global Edit button. #[test] From a7654fc63850be4ca7a0c42f05acbb0077e6aa2a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 16:17:26 -0800 Subject: [PATCH 58/71] xtask: test-lint matches base tests by place and keeps route kinds apart - never-run in changed mode lints the file as it was at the base and matches a test by its name and its place among tests of that name, so a test that was already off is not counted again when lines move. - A file reached by name inherits only the gates of named declarations, and one reached through #[path] only those of #[path] declarations. - The changed-file walk also reads the base child declarations of a #[path]-loaded file, so a removed `mod child;` still reaches the child. - reads-source classifies the outer path step, not a join nested in its argument. - mirror treats complete raw string literals as keys. - A raw cfg value keeps the quotes inside it (r#""unix""# is not unix). - census keeps word boundaries, so `k as usize` reads `k` and the local `kasusize` does not. - fixture-only finds a for loop's `in` across line breaks. --- xtask/src/test_lint.rs | 243 +++++++++++++++++++++++++++++++++-------- 1 file changed, 197 insertions(+), 46 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index fe0090fa33..40ac3b2f25 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -330,7 +330,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. let seeds: Vec<String> = changed.keys().cloned().collect(); let below: Vec<String> = - descendants(&seeds, &files, &overrides, &base_overrides, &read_work).into_iter().filter(|p| !changed.contains_key(p)).collect(); + descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec<String> = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); @@ -340,14 +340,17 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let base_gates = module_gates(&gated, &read_base, &base_overrides); let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - // The base's `never-run` hits, computed once per file on its first parent-attributed hit. - let base_off: RefCell<HashMap<String, HashSet<(String, usize)>>> = RefCell::new(HashMap::new()); + // The base's `never-run` hits on the file as it was at the base (the current source when the + // file is new or moved), computed once per file on its first parent-attributed hit. + let base_off: RefCell<HashMap<String, (String, Vec<Hit>)>> = RefCell::new(HashMap::new()); let newly_off = |path: &str, src: &str, hit: &Hit| { let mut cache = base_off.borrow_mut(); - let off = cache - .entry(path.to_owned()) - .or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()); - !off.contains(&(hit.test.clone(), hit.line)) + let (base_src, off) = cache.entry(path.to_owned()).or_insert_with(|| { + let base_src = read_base(path).unwrap_or_else(|| src.to_owned()); + let off = lint_file(path, &base_src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).collect(); + (base_src, off) + }); + !already_off(off, base_src, src, hit) }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { @@ -369,11 +372,21 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { finish(&counted, older, present.len(), &base) } -/// Whether `base`, the hits of the same source under the base's gates, has a `never-run` hit for the -/// test of `hit`. Tests of one name in different inline modules are told apart by their line. -#[cfg(test)] -fn already_off(base: &[Hit], hit: &Hit) -> bool { - base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +/// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test +/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so +/// lines that moved still match and tests of one name in different inline modules stay apart. +fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { + let place = test_place(src, &hit.test, hit.line); + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { + Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + None => h.line == hit.line, + }) +} + +/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. +fn test_place(src: &str, name: &str, line: usize) -> Option<usize> { + let lines = Lines::new(src); + tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -387,13 +400,15 @@ fn module_dir(p: &str) -> String { /// The files of `files` that the files `start` load, directly or through modules in between: the /// files under their module directories and the files their current or base `#[path]` declarations load. /// A file loaded through `#[path]` also loads the modules it declares by name from its own directory -/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read`. +/// (`mod child;` in `impl/platform.rs` loads `impl/child.rs`), read through `read` and, for the +/// declarations a change removed, through `read_base`. fn descendants( start: &[String], files: &[String], overrides: &Overrides, base_overrides: &Overrides, read: &dyn Fn(&str) -> Option<String>, + read_base: &dyn Fn(&str) -> Option<String>, ) -> Vec<String> { let mut seen: BTreeSet<String> = start.iter().cloned().collect(); let mut frontier: Vec<String> = start.to_vec(); @@ -404,7 +419,12 @@ fn descendants( return vec![]; } let dir = p.rsplit_once('/').map_or("", |(d, _)| d); - read(p).map_or(vec![], |src| declared_names(&src).into_iter().flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]).collect()) + [read(p), read_base(p)] + .into_iter() + .flatten() + .flat_map(|src| declared_names(&src)) + .flat_map(|n| [format!("{dir}/{n}.rs"), format!("{dir}/{n}/")]) + .collect() }; let dirs: Vec<String> = frontier.iter().map(|p| module_dir(p)).chain(frontier.iter().flat_map(beside)).collect(); let next: Vec<String> = files @@ -973,6 +993,25 @@ fn norm(b: &[u8]) -> String { String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::<Vec<u8>>()).into_owned() } +/// [`norm`], except that whitespace between two identifier characters becomes one space, so +/// `k as usize` stays three words and `kasusize` stays one. Removing the spaces gives [`norm`]. +fn norm_words(b: &[u8]) -> String { + let mut out = vec![]; + let mut gap = false; + for &c in b { + if c.is_ascii_whitespace() { + gap = true; + continue; + } + if gap && is_ident(c) && out.last().copied().is_some_and(is_ident) { + out.push(b' '); + } + gap = false; + out.push(c); + } + String::from_utf8_lossy(&out).into_owned() +} + /// Line starts, to turn byte offsets into 1-based lines. struct Lines(Vec<usize>); @@ -1545,7 +1584,7 @@ fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> { helpers_in(from, to).is_empty() && !rejects(body) && !inside.is_empty() - && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::<Vec<_>>(), var)) + && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::<Vec<_>>(), var)) }; for at in words(m, b"for", v.t.open, v.t.close) { let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue }; @@ -1788,10 +1827,10 @@ fn weak_predicate_within(pred: &str, depth: usize) -> bool { } /// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares -/// a lookup or parse with the entry itself. +/// a lookup or parse with the entry itself. `args` are written as [`norm_words`] gives them. fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { match guard_arg_count(name) { - 1 => args.first().is_some_and(|a| weak_predicate(a)), + 1 => args.first().is_some_and(|a| weak_predicate(&a.replace(' ', ""))), 2 if name.ends_with("_ne") => false, 2 => match args { [a, b, ..] => (round_trip_call(a, var) && is_entry(b, var)) || (round_trip_call(b, var) && is_entry(a, var)), @@ -1801,7 +1840,7 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } } -/// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole +/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole /// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so /// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's /// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is @@ -1826,20 +1865,16 @@ fn round_trip_call(op: &str, var: &str) -> bool { }) } -/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or -/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`). +/// Whether `s`, written as [`norm_words`] gives it, reads the binding `var`: a whole word that is not +/// a field or path segment (`config.k`, `m::k`), alone or cast (`k as usize`). `kasusize` is one word. fn reads_ident(s: &str, var: &str) -> bool { - const PRIMITIVES: &[&str] = - &["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"]; let b = s.as_bytes(); - let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident); !var.is_empty() && s.match_indices(var).any(|(at, _)| { let end = at + var.len(); let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.'); let path = at > 1 && &b[at - 2..at] == b"::"; - let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends))); - !(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast) + !(at > 0 && is_ident(b[at - 1])) && !field && !path && !b.get(end).copied().is_some_and(is_ident) }) } @@ -3137,10 +3172,11 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { // The final path step names the file read: the last literal of `root.join("src/lib.rs")` // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the // extension of a final `.with_extension("json")`. A final step whose argument is not a - // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. + // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on + // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { let step = |s: &'static str| { - arg.rfind(s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", @@ -3161,6 +3197,35 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { out } +/// The offset of the last `pat` in `expr` outside every bracket and string literal. +fn rfind_outer(expr: &str, pat: &str) -> Option<usize> { + let b = expr.as_bytes(); + let (mut depth, mut in_str, mut found) = (0usize, false, None); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + if depth == 0 && b[i..].starts_with(pat.as_bytes()) { + found = Some(i); + } + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth = depth.saturating_sub(1), + _ => {} + } + } + i += 1; + } + found +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3284,12 +3349,22 @@ fn norm_outside_literals(b: &[u8]) -> String { String::from_utf8_lossy(&out).into_owned() } +/// The contents of a complete raw string literal written after its `r`: `"a"` and `#"a"#` give `a`, +/// and `#""a""#` gives `"a"`. `None` when `s` is not one whole literal. +fn raw_literal_body(s: &str) -> Option<&str> { + let hashes = s.len() - s.trim_start_matches('#').len(); + let close = format!("\"{}", "#".repeat(hashes)); + let body = s[hashes..].strip_prefix('"')?.strip_suffix(close.as_str())?; + (!body.contains(close.as_str())).then_some(body) +} + /// An argument that names an entry rather than a quantity: a string or integer literal, or a local, /// field or indexed element (`"Swatches"`, `3`, `&doc`, `front[0]`). fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), None => false, @@ -3406,9 +3481,9 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(Strin // A `for` pattern binds its names inside the loop body only, to values the loop produces. let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { let Some((open, close)) = let_body(body, at + 3) else { return false }; - let head = String::from_utf8_lossy(&body[at + 3..open]); - let Some((pattern, _)) = head.split_once(" in ") else { return false }; - let pattern = norm(pattern.as_bytes()); + // `in` is found as a word, so a line break around it still ends the pattern. + let Some(&kw) = words(body, b"in", at + 3, open).first() else { return false }; + let pattern = norm(&body[at + 3..kw]); open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() }); // A match arm's pattern binds its names inside that arm only, and a closure's parameters @@ -3753,7 +3828,7 @@ fn cfg_value(p: &str, t: &Target) -> Option<bool> { // An ordinary string is compared by its decoded value (`"\x6cinux"` is `linux`); a raw string's // contents are kept as written. let (key, value) = p.split_once('=').map_or((p, String::new()), |(k, v)| match v.strip_prefix('r') { - Some(raw) => (k, raw.trim_matches('#').trim_matches('"').to_owned()), + Some(raw) => (k, raw_literal_body(raw).unwrap_or(raw).to_owned()), None => (k, unescape(v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v))), }); let value = value.as_str(); @@ -3960,8 +4035,9 @@ struct Loaded<'a> { /// items, inline modules and file around them, with the 1-based lines of those declarations and /// attributes. Several declarations that load the file join into one `any(all(…), …)`. `None` /// when `src` loads no such file. `owns_dir` reads `parent` as loaded through `#[path]`, which -/// declares its modules in its own directory, as a `mod.rs` or a crate root does. -fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Option<(Vec<String>, Vec<usize>)> { +/// declares its modules in its own directory, as a `mod.rs` or a crate root does. `via` keeps only +/// the declarations that load `want` by name (`Named`) or through `#[path]` (`Path`). +fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool, via: Via) -> Option<(Vec<String>, Vec<usize>)> { let m = mask(src); let lines = Lines::new(src); let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); @@ -3993,13 +4069,14 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded, owns_dir: bool) -> Opti let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at); let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path; let fallback = match path_attr(&m, src.as_bytes(), item, at) { - Some(rel) => overrides_here(&rel), + Some(rel) => via != Via::Named && overrides_here(&rel), None => { - &m[start..end] == want.name.as_bytes() + via != Via::Path + && &m[start..end] == want.name.as_bytes() && [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path) } }; - let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); + let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| via != Via::Named && overrides_here(rel)).map(|(c, _)| c.as_str()).collect(); let route = match (fallback, selected.is_empty(), conditional.is_empty()) { (true, _, true) => None, (true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(","))), @@ -4294,7 +4371,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Over // can both load it): its tests are off only when every one of them leaves them out. if via != Via::Path { found.extend(candidates.iter().filter_map(|c| { - read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, named(c))) + read(c).inspect(|_| parent_read = true).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, named(c))) })); } if chain.is_empty() { @@ -4305,7 +4382,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Over continue; } let want = Loaded { path: at, name: &name, chain: inline }; - found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false)).map(|f| (c.clone(), f, Via::Any))); + found.extend(read(c).and_then(|s| declared_cfgs(&s, c, &want, false, via)).map(|f| (c.clone(), f, Via::Any))); } // A file loaded through `#[path]` owns its directory like a `mod.rs`: its `mod child;` // loads the `child.rs` beside it (`impl/platform.rs` loads `impl/child.rs`). @@ -4313,7 +4390,7 @@ fn module_gate(at: &str, read: &dyn Fn(&str) -> Option<String>, overrides: &Over .keys() .filter(|k| via != Via::Path && k.as_str() != at && !owns_its_dir(k) && k.rsplit_once('/').is_some_and(|(d, _)| d == module_dir)); for owner in path_loaded { - found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true)).map(|f| (owner.clone(), f, Via::Path))); + found.extend(read(owner).and_then(|s| declared_cfgs(&s, owner, &want, true, via)).map(|f| (owner.clone(), f, Via::Path))); } } if via == Via::Path || beside_roots(at) { @@ -4519,6 +4596,8 @@ mod tests { assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry"); let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n"; assert_eq!(census(fixed_cast), [], "a cast of a fixed key"); + let one_word = "#[test]\nfn t() {\n let kasusize = 3;\n for k in KEYS {\n assert_eq!(lookup(kasusize), k);\n }\n}\n"; + assert_eq!(census(one_word), [], "a fixed local spelled like a cast of the entry"); let field = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n"; assert_eq!(census(field), [], "a field or path named like the binding is a fixed key"); @@ -6084,6 +6163,8 @@ mod tests { assert_eq!(only("mirror", order), [], "positions of two entries in one list"); let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n"; assert_eq!(only("mirror", commented), [], "a comment beside a key"); + let raw = "#[test]\nfn t() {\n assert_eq!(at(r#\"B\"#), at(r#\"A\"#) + 1);\n assert_eq!(at(r\"B\"), at(r\"A\") + 1);\n}\n"; + assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; @@ -6217,7 +6298,7 @@ mod tests { #[test] fn never_run_follows_the_cfg_around_the_mod_declaration() { let child = Loaded { path: "src/child.rs", name: "child", chain: &[] }; - let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false).map(|(p, _)| p); + let declared = |src: &str, want: &Loaded| declared_cfgs(src, "src/lib.rs", want, false, Via::Any).map(|(p, _)| p); let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared(inner, &child), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; @@ -6339,10 +6420,25 @@ mod tests { let base = lint_file(path, src, &ctx()); let now = lint_file(path, src, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); - let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, h)).map(|h| h.line).collect(); + let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, src, src, h)).map(|h| h.line).collect(); assert_eq!(off.len(), 1, "only the test in `b` is newly off: {off:?}"); } + #[test] + fn a_test_off_at_the_base_is_matched_in_the_base_source() { + // At the base an inline module gate turned the test off; the change removes that gate and + // gates the parent instead, which also moves the test up a line. + let path = "crates/x/src/child.rs"; + let before = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\n#[cfg(target_os = \"macos\")]\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod a {\n #[test]\n fn u() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<&str> = + now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.test.as_str()).collect(); + assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6430,7 +6526,56 @@ mod tests { assert_eq!(hits_in(&below, test, &ctx), [], "the path-loaded file does not load impl/platform/child.rs"); let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; let all: Vec<String> = files.keys().map(|p| (*p).to_owned()).collect(); - assert!(descendants(&seeds, &all, &overrides, &Overrides::new(), &read).contains(&child), "a change to platform.rs reaches child.rs"); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child), + "a change to platform.rs reaches child.rs" + ); + } + + #[test] + fn a_named_route_takes_only_the_gates_of_named_declarations() { + // `parent.rs` is loaded by name on macOS and through `#[path]` on Linux. Only the named route + // loads `parent/child.rs`; the `#[path]` route loads `child.rs` beside `parent.rs`. + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod parent;\n#[cfg(target_os = \"linux\")]\n#[path = \"parent.rs\"]\nmod p2;\n"), + ("crates/x/src/parent.rs", "mod child;\n"), + ("crates/x/src/parent/child.rs", ""), + ("crates/x/src/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (child, expected) in [("crates/x/src/parent/child.rs", vec![(2, "never-run")]), ("crates/x/src/child.rs", vec![])] { + let ctx = Ctx { module_cfgs: module_cfgs(&[child.to_owned()], &read, &overrides), ..self::ctx() }; + assert_eq!(hits_in(child, test, &ctx), expected, "{child}"); + } + } + + #[test] + fn a_removed_child_declaration_still_reaches_the_child() { + let work: HashMap<&str, &str> = [ + ( + "crates/x/src/lib.rs", + "#[path = \"impl/platform.rs\"]\nmod platform;\n#[cfg(target_os = \"macos\")]\n#[path = \"impl/child.rs\"]\nmod child;\n", + ), + ("crates/x/src/impl/platform.rs", ""), + ("crates/x/src/impl/child.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| work.get(p).map(|s| (*s).to_owned()); + let read_base = |p: &str| if p == "crates/x/src/impl/platform.rs" { Some("mod child;\n".to_owned()) } else { read(p) }; + let overrides = path_overrides(work.iter().map(|(p, s)| (*p, *s))); + let seeds = ["crates/x/src/impl/platform.rs".to_owned()]; + let all: Vec<String> = work.keys().map(|p| (*p).to_owned()).collect(); + let child = "crates/x/src/impl/child.rs".to_owned(); + assert!(!descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &|_| None).contains(&child)); + assert!( + descendants(&seeds, &all, &overrides, &Overrides::new(), &read, &read_base).contains(&child), + "the base `mod child;` that the change removed still leads to child.rs" + ); } #[test] @@ -6594,7 +6739,7 @@ mod tests { let base_ctx = Ctx { module_cfgs: module_cfgs(&paths, &read_base, &base_overrides), ..ctx() }; let files = work_files.iter().map(|(p, _)| (*p).to_owned()).chain(paths.iter().cloned()).collect::<Vec<_>>(); assert!( - descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None).contains(&child.to_owned()), + descendants(&[a.to_owned()], &files, &overrides, &base_overrides, &|_| None, &|_| None).contains(&child.to_owned()), "the removed route still reaches the shared tests" ); for lines in [Some(BTreeSet::new()), Some([20].into_iter().collect()), None] { @@ -6602,7 +6747,7 @@ mod tests { assert!(!gate_changed(gates.get(child), &changed), "the surviving route was not edited"); let parent_changed = route_gate_changed(child, gates.get(child), base_gates.get(child), &base_overrides, &changed); assert!(parent_changed, "deletions and shifted lines still change a base route"); - assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), &hit), ran); + assert_eq!(parent_changed && !already_off(&lint_file(child, test, &base_ctx), test, test, &hit), ran); assert!( route_gate_changed(child, gates.get(child), None, &base_overrides, &changed), "a base route parent counts even without inherited predicates" @@ -6683,6 +6828,8 @@ mod tests { assert_eq!(cfg_value("target_os=\"\\u{6c}inux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"linux\"", linux), Some(true)); assert_eq!(cfg_value("target_os=r\"\\x6cinux\"", linux), Some(false), "a raw string is not decoded"); + assert_eq!(cfg_value("target_family=r#\"unix\"#", linux), Some(true)); + assert_eq!(cfg_value("target_family=r#\"\"unix\"\"#", linux), Some(false), "quotes inside a raw string are part of the value"); } #[test] @@ -6705,7 +6852,7 @@ mod tests { let base: Overrides = [("crates/x/src/shared.rs".to_owned(), vec![("crates/x/src/bin/tool.rs".to_owned(), vec![])])].into_iter().collect(); let seeds: Vec<String> = got.keys().cloned().collect(); let files = ["crates/x/src/shared.rs".to_owned()]; - assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None), ["crates/x/src/shared.rs"]); + assert_eq!(descendants(&seeds, &files, &Overrides::new(), &base, &|_| None, &|_| None), ["crates/x/src/shared.rs"]); } #[test] @@ -6720,7 +6867,7 @@ mod tests { ]; let overrides = path_overrides(sources); let read = |p: &str| sources.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); - let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read); + let found = descendants(&["src/solids/graphics.rs".to_owned()], &files, &overrides, &Overrides::new(), &read, &|_| None); assert_eq!(found, ["src/solids/map_art.rs", "src/solids/tests_map_art.rs"], "through map_art.rs, and not other.rs"); } @@ -6817,6 +6964,8 @@ mod tests { let joined = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file"); + let nested = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(if root.join(\"config.rs\").exists() { \"a.json\" } else { \"b.json\" })).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", nested), [], "a join inside the outer join's argument"); let extension = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"sample.rs\").with_extension(\"json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", extension), [], "a final extension that is not rs"); let to_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"lib.txt\").with_extension(\"rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; @@ -6856,6 +7005,8 @@ mod tests { fn a_for_binding_shadows_the_outer_one_in_its_body() { let looped = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n assert_eq!(n, 1);\n }\n}\n"; assert_eq!(only("fixture-only", looped), []); + let broken = "#[test]\nfn t() {\n let n = 0;\n for n in\n results()\n {\n assert_eq!(n, 1);\n }\n}\n"; + assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); } From e19e96f810de7342f8c5bd3e6d693a9ee9a83f6e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:06:07 -0800 Subject: [PATCH 59/71] xtask: test-lint reads base roots, module scopes and whole literals - Changed mode builds the base's target-root routes from the base tree, so a deleted tests/<root>.rs still counts as loading tests/common/mod.rs. - A base test is matched by its name, its inline modules and its place among same-named tests in them, so removing `mod a` does not let `a::t` hide a newly off `b::t`. - reads-source looks through grouping around the read path and names a file only from a complete literal, a format!/concat! call or Path::new/PathBuf::from; `"data.json".trim_end_matches(".rs")` no longer counts as a .rs file. - mirror keys keep a raw literal whole up to its own delimiter, and a key must be one complete string literal. - for, if let, while let, let and match patterns keep word boundaries (`mut n` binds `n`), and a struct pattern's braces are not taken as the loop or if-let body. - #[path] and cfg_attr path values accept raw string literals. --- xtask/src/test_lint.rs | 320 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 289 insertions(+), 31 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 40ac3b2f25..449885209f 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -293,6 +293,12 @@ fn read_small(root: &Path, path: &str) -> Option<String> { (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } +/// The scanned files of the tree at `base`, or `None` when Git cannot list it. +fn base_files(root: &Path, base: &str) -> Option<Vec<String>> { + let list = git(root, &["ls-tree", "-r", "-z", "--name-only", base]).ok()?; + Some(list.split('\0').filter(|p| !p.is_empty() && is_scanned(p)).map(str::to_owned).collect()) +} + /// Cache successful and missing reads for one source tree. fn cached_read(read: impl Fn(&str) -> Option<String>) -> impl Fn(&str) -> Option<String> { let cache = RefCell::new(HashMap::<String, Option<String>>::new()); @@ -324,7 +330,10 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { // instead of reading the tree, and the target roots beside a shared `tests/<dir>/mod.rs`. let overrides = with_root_routes(discover_path_overrides(root, None, &read_work), &files); let read_base = cached_read(|p| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE)); - let base_overrides = with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &files); + // The base's target roots come from the base tree: a root the change deleted still loaded the + // shared module beside it. + let base_overrides = + with_root_routes(discover_path_overrides(root, Some(&base), &read_base), &base_files(root, &base).unwrap_or_else(|| files.clone())); // Files a changed file loads, directly or through other modules: a `cfg` added to their `mod` // declaration can turn their tests off without a change to them. // Deleted files seed the walk too: a module they loaded at the base may have lost its only CI route. @@ -373,20 +382,49 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } /// Whether `base`, the hits of `base_src` under the base's gates, has a `never-run` hit for the test -/// of `hit` in `src`. A test is matched by its name and its place among the tests of that name, so -/// lines that moved still match and tests of one name in different inline modules stay apart. +/// of `hit` in `src`. A test is matched by its name, the inline modules around it and its place +/// among the tests of that name in those modules, so lines that moved still match and tests of one +/// name in different inline modules stay apart, even when a change removes one of the modules. fn already_off(base: &[Hit], base_src: &str, src: &str, hit: &Hit) -> bool { let place = test_place(src, &hit.test, hit.line); - base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match place { - Some(place) => test_place(base_src, &h.test, h.line) == Some(place), + base.iter().filter(|h| h.rule == Rule::NeverRun && h.test == hit.test).any(|h| match &place { + Some(place) => test_place(base_src, &h.test, h.line).as_ref() == Some(place), None => h.line == hit.line, }) } -/// The index of the test `name` whose `fn` is on `line` among the tests of that name in `src`. -fn test_place(src: &str, name: &str, line: usize) -> Option<usize> { +/// The inline modules around the test `name` whose `fn` is on `line` in `src` (outermost first), +/// and its index among the tests of that name in the same modules. +fn test_place(src: &str, name: &str, line: usize) -> Option<(Vec<String>, usize)> { let lines = Lines::new(src); - tests_in(&mask(src)).iter().filter(|t| t.name == name).position(|t| lines.of(t.fn_at) == line) + let m = mask(src); + let named: Vec<(Vec<String>, usize)> = + tests_in(&m).iter().filter(|t| t.name == name).map(|t| (inline_modules(&m, t.fn_at), lines.of(t.fn_at))).collect(); + let (scope, _) = named.iter().find(|(_, l)| *l == line)?; + let index = named.iter().filter(|(s, _)| s == scope).position(|(_, l)| *l == line)?; + Some((scope.clone(), index)) +} + +/// The names of the inline `mod <name> { … }` blocks around `at` in the masked text `m`, outermost +/// first. +fn inline_modules(m: &[u8], at: usize) -> Vec<String> { + let mut open: Vec<Option<String>> = vec![]; + for (i, &c) in m.iter().enumerate().take(at) { + match c { + b'{' => { + let head = m[..i].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + let before = head[..head.len() - name].trim_ascii_end(); + let keyword = name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident); + open.push(keyword.then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned())); + } + b'}' => { + open.pop(); + } + _ => {} + } + } + open.into_iter().flatten().collect() } /// The directory holding the modules that the file `p` declares by name: its own directory for @@ -3175,13 +3213,15 @@ fn reads_source_hits(file: &File) -> Vec<Hit> { // literal (`.join(name)`, `.with_extension(ext)`) names an unknown file. Only steps on // the outer path count: a `.join` inside another step's argument does not. b"read_to_string" => { + // Grouping around the whole argument hides no step: `(root.join(…))`. + let arg = ungroup(arg.strip_suffix(',').unwrap_or(&arg)); let step = |s: &'static str| { - rfind_outer(&arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) + rfind_outer(arg, s).and_then(|at| matching(arg.as_bytes(), at + s.len() - 1).map(|close| (at, s, &arg[at + s.len()..close]))) }; match [".join(", ".with_file_name(", ".with_extension("].map(step).into_iter().flatten().max_by_key(|&(at, _, _)| at) { - Some((_, ".with_extension(", ext)) => ext.trim_start_matches('r').trim_matches('#') == "\"rs\"", - Some((_, _, last)) => last_literal(last).is_some_and(|l| l.ends_with(".rs\"")), - None => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), + Some((_, ".with_extension(", ext)) => file_literal(ext) == Some("\"rs\""), + Some((_, _, last)) => file_literal(last).is_some_and(|l| l.ends_with(".rs\"")), + None => file_literal(arg).is_some_and(|l| l.ends_with(".rs\"")), } } _ => arg.trim_end_matches('#').ends_with(".rs\""), @@ -3226,6 +3266,81 @@ fn rfind_outer(expr: &str, pat: &str) -> Option<usize> { found } +/// The offset of the `)` that closes the `(` at `open` in `expr`, skipping string literals. +fn outer_close(expr: &str, open: usize) -> Option<usize> { + let b = expr.as_bytes(); + let (mut depth, mut in_str) = (0usize, false); + let mut i = open; + while i < b.len() { + let c = b[i]; + if in_str { + if c == b'\\' { + i += 1; + } else if c == b'"' { + in_str = false; + } + } else { + match c { + b'"' if !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) => in_str = true, + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(i); + } + } + _ => {} + } + } + i += 1; + } + None +} + +/// A whitespace-free expression without the references and parentheses around all of it: +/// `&(root.join("a"))` gives `root.join("a")`. +fn ungroup(mut expr: &str) -> &str { + loop { + let inner = expr.trim_start_matches('&'); + match inner.strip_prefix('(') { + Some(_) if outer_close(inner, 0) == Some(inner.len() - 1) => expr = &inner[1..inner.len() - 1], + _ => return inner, + } + } +} + +/// `s` when it is one complete ordinary string literal (`"a.rs"`, not `"a"+"b"`), or the body of +/// one complete raw string literal in quotes (`r#"a.rs"#` gives `"a.rs"`). +fn whole_literal(s: &str) -> Option<&str> { + if s.starts_with('"') { + return (s.len() > 1 && string_end(s.as_bytes(), 1) == s.len() && s.ends_with('"')).then_some(s); + } + let rest = s.strip_prefix('r')?; + let hashes = rest.len() - rest.trim_start_matches('#').len(); + raw_literal_body(rest).map(|_| &rest[hashes..rest.len() - hashes]) +} + +/// The literal that names the file of a whitespace-free path expression, quotes included: one +/// complete string literal, the file literal of a `format!`-family or `concat!` call +/// ([`last_literal`]), or the same inside `Path::new(…)` or `PathBuf::from(…)`. `None` for any +/// other expression: `"data.json".trim_end_matches(".rs")` names `data.json`, not its last literal. +fn file_literal(expr: &str) -> Option<&str> { + let e = ungroup(expr.strip_suffix(',').unwrap_or(expr)); + if let Some(l) = whole_literal(e) { + return Some(l); + } + let open = e.find('(')?; + if outer_close(e, open) != Some(e.len() - 1) { + return None; + } + let head = e[..open].trim_start_matches("std::").trim_start_matches("path::"); + match head { + "format!" | "format_args!" | "concat!" => last_literal(e), + "Path::new" | "PathBuf::from" => file_literal(&e[open + 1..e.len() - 1]), + _ => None, + } +} + /// The last string literal in a (whitespace-free) expression, quotes included. Inside a /// `format!`-family call, an argument is not the file name, so the format string is returned /// instead: `format!("fixtures/{}.txt", "lib.rs")` names a `.txt` file. @@ -3341,6 +3456,13 @@ fn norm_outside_literals(b: &[u8]) -> String { } else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) { in_str = true; out.push(c); + } else if c == b'r' && !(i > 0 && is_ident(b[i - 1])) && matches!(b[i + 1..].iter().find(|&&h| h != b'#'), Some(b'"')) { + // A raw literal runs to its own closing delimiter: the `"` in `r#"A" B"#` does not end it. + let mut sink = vec![]; + let end = after_ident(b, &mut sink, i, false); + out.extend_from_slice(&b[i..end]); + i = end; + continue; } else if !c.is_ascii_whitespace() { out.push(c); } @@ -3363,7 +3485,7 @@ fn raw_literal_body(s: &str) -> Option<&str> { fn key_like(arg: &str) -> bool { let arg = arg.trim_start_matches("&mut").trim_start_matches('&'); match arg.as_bytes().first() { - Some(b'"') => arg.len() > 1 && arg.ends_with('"'), + Some(b'"') => whole_literal(arg).is_some(), Some(b'r') if arg[1..].starts_with(['"', '#']) => raw_literal_body(&arg[1..]).is_some(), Some(c) if c.is_ascii_digit() => arg.bytes().all(|c| c.is_ascii_digit() || c == b'_'), Some(_) => arg.bytes().all(|c| is_ident(c) || matches!(c, b'.' | b'[' | b']' | b':')), @@ -3480,10 +3602,12 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(Strin let found = let_init(body, name, before); // A `for` pattern binds its names inside the loop body only, to values the loop produces. let loop_at = words(body, b"for", 0, before).into_iter().rev().find(|&at| { - let Some((open, close)) = let_body(body, at + 3) else { return false }; - // `in` is found as a word, so a line break around it still ends the pattern. - let Some(&kw) = words(body, b"in", at + 3, open).first() else { return false }; - let pattern = norm(&body[at + 3..kw]); + // `in` is found as a word outside the pattern's brackets, so a line break around it still + // ends the pattern, and the braces of `for Row { n } in …` are not the loop body. + let Some(kw) = words(body, b"in", at + 3, before).into_iter().find(|&kw| bracket_depth(&body[at + 3..kw]) == 0) else { return false }; + let Some((open, close)) = block_after(body, kw + 2) else { return false }; + // Words stay apart, so `mut n` binds `n`. + let pattern = norm_words(&body[at + 3..kw]); open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() }); // A match arm's pattern binds its names inside that arm only, and a closure's parameters @@ -3564,7 +3688,7 @@ fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> { } // A guard (`Some(x) if x == n`) reads names; it does not bind them. let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow); - let pattern = norm(&body[start..guard]); + let pattern = norm_words(&body[start..guard]); if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { continue; } @@ -3609,9 +3733,8 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u [&b"if"[..], b"while"].into_iter().find(|k| head.ends_with(k) && !head[..head.len() - k.len()].last().copied().is_some_and(is_ident)); if keyword.is_some() { // `if let` and `while let` bind the pattern's names inside their body only. - if let Some((open, close)) = let_body(body, n0) { - let pattern = norm(&body[n0..open]); - let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); + if let Some((eq, open, close)) = let_body(body, n0) { + let pattern = norm_words(&body[n0..eq]); if open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { found = Some((None, at)); } @@ -3629,7 +3752,7 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u found = Some((if is_mut { None } else { init }, at)); } else if !plain { // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). - let pattern = norm(&body[n0..stop]); + let pattern = norm_words(&body[n0..stop]); let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { found = Some((None, at)); @@ -3639,9 +3762,44 @@ fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, u found } -/// The braces of the body of an `if let` or `while let` whose pattern starts at `from`: the first -/// `{` outside parentheses and brackets, and its match. -fn let_body(body: &[u8], from: usize) -> Option<(usize, usize)> { +/// The `=` that ends the pattern of an `if let` or `while let` starting at `from`, and the braces of +/// its body after the scrutinee ([`block_after`]). The `=` sits outside every bracket, so the braces +/// of a struct pattern (`if let Row { n } = …`) are part of the pattern, and it is not part of `==`, +/// `=>`, `..=`, `<=`, `>=` or `!=`. +fn let_body(body: &[u8], from: usize) -> Option<(usize, usize, usize)> { + let mut depth = 0usize; + for (i, &c) in body.iter().enumerate().skip(from) { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' if depth == 0 => return None, + b')' | b']' | b'}' => depth -= 1, + b';' if depth == 0 => return None, + b'=' if depth == 0 + && !matches!(body.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| body[j]), Some(b'=' | b'.' | b'<' | b'>' | b'!')) => + { + return block_after(body, i + 1).map(|(open, close)| (i, open, close)); + } + _ => {} + } + } + None +} + +/// The depth of the brackets left open at the end of `b`. +fn bracket_depth(b: &[u8]) -> isize { + b.iter() + .map(|&c| match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }) + .sum() +} + +/// The braces of the block that follows an expression starting at `from`: the first `{` outside +/// parentheses and brackets, and its match. +fn block_after(body: &[u8], from: usize) -> Option<(usize, usize)> { let mut depth = 0usize; for (i, &c) in body.iter().enumerate().skip(from) { match c { @@ -4202,20 +4360,37 @@ fn path_overrides<'a>(sources: impl IntoIterator<Item = (&'a str, &'a str)>) -> out } -/// The string value of a `#[path = "…"]` attribute in `m[from..to]`. +/// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a +/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> { words(m, b"path", from, to).into_iter().find_map(|at| { let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); let eq = skip_ws(m, at + 4); - let q = skip_ws(m, eq + 1); - if !attr || m.get(eq) != Some(&b'=') || m.get(q) != Some(&b'"') { + let mut q = skip_ws(m, eq + 1); + if !attr || m.get(eq) != Some(&b'=') { return None; } - let close = find(m, b"\"", q + 1)?; - Some(String::from_utf8_lossy(&src[q + 1..close]).into_owned()) + let hashes = if m.get(q) == Some(&b'r') { + let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count(); + q += 1 + h; + h + } else { + 0 + }; + if m.get(q) != Some(&b'"') { + return None; + } + let close: Vec<u8> = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(m, &close, q + 1)?; + Some(String::from_utf8_lossy(&src[q + 1..end]).into_owned()) }) } +/// The value of a whitespace-free `path=<literal>` argument, for an ordinary or a raw string literal. +fn path_arg(arg: &str) -> Option<&str> { + whole_literal(arg.strip_prefix("path=")?).map(|l| &l[1..l.len() - 1]) +} + /// The `#[cfg_attr(<condition>, path = "…")]` overrides in `m[from..to]`, each as its condition and /// path. fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> { @@ -4232,7 +4407,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, let mut start = first + 1; for cut in cuts[1..].iter().copied().chain([text.len()]) { let arg = text.get(start..cut).unwrap_or(""); - if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) { + if let Some(rel) = path_arg(arg) { out.push((text[..first].to_owned(), rel.to_owned())); } start = cut + 1; @@ -6167,6 +6342,10 @@ mod tests { assert_eq!(only("mirror", raw), [], "raw string keys"); let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n"; assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry"); + let raw_quote = "#[test]\nfn t() {\n assert_eq!(at(r#\"A\" B\"#), at(r#\"A\"B\"#) + 1);\n}\n"; + assert_eq!(only("mirror", raw_quote), [], "a quote inside a raw key does not end it"); + let computed = "#[test]\nfn t() {\n assert_eq!(label(\"A\".to_owned() + \"B\"), label(\"C\") + 1);\n}\n"; + assert_eq!(only("mirror", computed), [(3, "mirror")], "a computed string is not an entry key"); let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n"; assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not"); let offset = @@ -6211,6 +6390,13 @@ mod tests { assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); let if_let = "#[test]\nfn t() {\n let x = 0;\n if let Some(x) = compute() {\n assert_eq!(x, 2);\n }\n}\n"; assert_eq!(only("fixture-only", if_let), [], "an `if let` binding shadows the outer one in its body"); + let struct_pattern = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", struct_pattern), [], "the braces of a struct pattern are not the body"); + let else_branch = "#[test]\nfn t() {\n let n = 0;\n if let Row { n } = compute() {\n consume(n);\n } else {\n assert_eq!(n, 0);\n }\n}\n"; + assert_eq!(only("fixture-only", else_branch), [(2, "fixture-only")], "the `else` branch sees the outer binding"); + let mut_pattern = + "#[test]\nfn t() {\n let n = 0;\n if let Some(mut n) = compute() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mut_pattern), [], "`mut n` in an `if let` binds `n`"); } #[test] @@ -6439,6 +6625,20 @@ mod tests { assert_eq!(off, ["u"], "`t` was already off at the base; only `u` is newly off"); } + #[test] + fn a_removed_namesake_module_does_not_hide_a_newly_off_test() { + // `a::t` was off at the base and `b::t` ran; the change deletes `mod a` and gates the parent, + // so `b::t` is now the only `t` in the file. + let path = "crates/x/src/child.rs"; + let before = "#[cfg(target_os = \"macos\")]\nmod a {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\nmod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let after = "mod b {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file(path, before, &ctx()); + let now = + lint_file(path, after, &Ctx { module_cfgs: [(path.to_owned(), vec!["target_os=\"macos\"".to_owned()])].into_iter().collect(), ..ctx() }); + let off: Vec<usize> = now.iter().filter(|h| h.rule == Rule::NeverRun && !already_off(&base, before, after, h)).map(|h| h.line).collect(); + assert_eq!(off, [3], "`b::t` is newly off"); + } + #[test] fn never_run_follows_a_tests_module_directory_under_src() { let files: HashMap<&str, &str> = @@ -6610,6 +6810,27 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn base_root_routes_come_from_the_base_tree() { + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let root = std::env::temp_dir().join(format!("test-lint-roots-{}-{unique}", std::process::id())); + std::fs::create_dir_all(root.join("crates/x/tests/common")).unwrap(); + git(&root, &["init", "--quiet"]).unwrap(); + std::fs::write(root.join("crates/x/tests/smoke.rs"), "mod common;\n").unwrap(); + std::fs::write(root.join("crates/x/tests/common/mod.rs"), "").unwrap(); + git(&root, &["add", "."]).unwrap(); + let base = git(&root, &["write-tree"]).unwrap(); + std::fs::remove_file(root.join("crates/x/tests/smoke.rs")).unwrap(); + let shared = "crates/x/tests/common/mod.rs"; + let now = vec![shared.to_owned()]; + assert!(with_root_routes(Overrides::new(), &now).get(shared).is_none_or(|r| r.is_empty()), "no root loads it now"); + let then = base_files(&root, &base).unwrap(); + let routes = with_root_routes(Overrides::new(), &then); + let parents: Vec<&str> = routes.get(shared).into_iter().flatten().map(|(p, _)| p.as_str()).collect(); + assert_eq!(parents, ["crates/x/tests/smoke.rs"], "the deleted root loaded it at the base"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn never_run_follows_a_path_selected_by_cfg_attr() { let files: HashMap<&str, &str> = [ @@ -6977,6 +7198,15 @@ mod tests { let format_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", format_rs), [(3, "reads-source")], "a format string that names a .rs file"); + let grouped_ext = "#[test]\nfn t() {\n let s = fs::read_to_string((root.join(\"sample.rs\").with_extension(ext))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", grouped_ext), [], "grouping around the argument hides no step"); + let grouped_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(&(root.join(\"src/lib.rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", grouped_rs), [(3, "reads-source")], "a grouped join that names a .rs file"); + let computed = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\".trim_end_matches(\".rs\"))).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", computed), [], "a computed file name is not its last literal"); + let wrapped = "#[test]\nfn t() {\n let s = fs::read_to_string(Path::new(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", wrapped), [(3, "reads-source")], "a literal inside Path::new"); let split = "#[test]\nfn t() {\n let s = fs::read_to_string(\n \"src/lib.rs\",\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; let found = lint_file("crates/x/src/tests.rs", split, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::ReadsSource).unwrap(); @@ -7009,6 +7239,12 @@ mod tests { assert_eq!(only("fixture-only", broken), [], "a line break after `in`"); let after = "#[test]\nfn t() {\n let n = 0;\n for n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; assert_eq!(only("fixture-only", after), [(2, "fixture-only")], "the outer binding after the loop"); + let mutable = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n n += 1;\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", mutable), [], "`mut n` binds `n`"); + let destructured = "#[test]\nfn t() {\n let n = 0;\n for Row { n } in rows() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", destructured), [], "the braces of a struct pattern are not the loop body"); + let mut_after = "#[test]\nfn t() {\n let n = 0;\n for mut n in results() {\n consume(n);\n }\n assert_eq!(n, 0);\n}\n"; + assert_eq!(only("fixture-only", mut_after), [(2, "fixture-only")], "the outer binding after a `mut` loop"); } #[test] @@ -7033,6 +7269,28 @@ mod tests { assert_eq!(only("never-run", comma), [], "a comma inside the condition's value"); let src = "#[cfg_attr(unix, path = \"a,b.rs\")]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]); + let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]); + } + + #[test] + fn path_attributes_accept_raw_strings() { + for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] { + assert_eq!(path_attr(&mask(src), src.as_bytes(), 0, src.len()).as_deref(), Some("shared.rs"), "{src}"); + } + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "mod a;\nmod b;\n"), + ("crates/x/src/a.rs", "#[path = r\"shared.rs\"]\nmod s;\n"), + ("crates/x/src/b.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"shared.rs\"]\nmod s;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let shared = "crates/x/src/shared.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); } #[test] From 21f9323fcf2ee91c7637f6ccb3d09014e1adde13 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:22:04 -0800 Subject: [PATCH 60/71] Tests: import_fuzz's two regression tests check that their input reaches the export svg_type_shifted_two_billion_points_exports_to_pdf now checks that the SVG import keeps the type's shift of more than 2,000,000,000 pt, and that the exported PDF leaves the type out, read back with the PDF importer. Before, it checked only that the export returned Ok, so an import that dropped or clamped the shift made it pass without reaching the bound. a_long_thin_shape_with_a_shadow_renders_and_exports now checks that the Affinity import gives exactly one shape with a drop shadow, more than 3,000,000 pt wide, before it renders and exports it. Before, an import that dropped the shadow made it pass without drawing one. The other 66 test-lint hits in import_fuzz.rs are property tests whose claim is that hostile input loads, renders and exports without a panic. Their helpers (survive, survive_library and the others) fail the case through TestCaseError, which the no-assertion rule does not count. --- crates/engine/tests/import_fuzz.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 9ff294a878..c6f02b9240 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -929,7 +929,20 @@ fn mutate_text(src: &str, cut: usize, edits: &[(usize, char)]) -> String { fn svg_type_shifted_two_billion_points_exports_to_pdf() { let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><text baseline-shift="-2147483649">f</text></svg>"#; let d = vectorcraft_svg::import(svg).unwrap(); - assert!(vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).is_ok()); + // The type opens with its shift, so the export below meets a glyph that far out. + let mut shifts = Vec::new(); + d.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + shifts.extend(t.runs.iter().map(|r| r.style.baseline_shift)); + } + }); + assert!(shifts.iter().any(|&s| s.abs() > 2e9), "baseline shifts read: {shifts:?}"); + let pdf = vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).unwrap(); + // The PDF leaves the type out: reading it back finds no type. + let back = vectorcraft_pdf::import(&pdf).unwrap(); + let mut text = 0; + back.walk(|n| text += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)))); + assert_eq!(text, 0, "type left out of the page"); } proptest! { @@ -8630,6 +8643,16 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() { let stream = canvas_stream(vec![with_effects(rectangle(10, (0.0, 0.0), (3_276_800.0, 50.0)), vec![shadow()])]); let bytes = affinity_sample_file(&stream, None); let doc = vectorcraft_engine::cmd::fileio::load("long.af", &bytes).unwrap().doc; + // The shape opens whole, with its shadow, so the exports below draw the shadow that far out. + let mut shadowed = Vec::new(); + doc.walk(|n| { + if n.appearance.effects.iter().any(|e| e.id == "stylize.dropShadow") { + shadowed.push(n.id); + } + }); + assert_eq!(shadowed.len(), 1, "one shape with a drop shadow"); + let width = doc.bounds_of(&shadowed, false).map(|r| r.width()); + assert!(width.is_some_and(|w| w > 3_000_000.0), "the shape is {width:?} pt wide"); survive("long shape", || Some(doc)).unwrap(); } From c58415b30725a45b778783b00d9577090c35b33f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:24:39 -0800 Subject: [PATCH 61/71] Tests: color and effects tests check behavior, not their own tables Parse tests in the color crate looped over every id or label and parsed it back. Blend modes, policies, harmony rules, recolor methods and WCAG categories parse by looking the text up in that same table, so those loops could not fail. They now parse representative ids, labels and spellings, and the edge cases: "Color" next to "Color Burn", empty text, and a label where only ids parse. - default_swatches_parse read swatch.rs as text. It now checks the built swatches: no two solid swatches share a color (a bad hex literal falls back to black), and the Sunset and Ocean stops equal the swatches their literals name. - loads_system_cmyk_icc ran only on macOS and returned early without the system profile. loads_icc_files_and_refuses_bad_ones runs on every native target: a missing file is an I/O error naming the path, a file that is not a profile is refused, and a built-in profile's bytes are refused for their name. - the_other_libraries_keep_classic_mixing_and_centered_midpoints is removed: those libraries are built with Gradient::new's defaults. - pixel_timings and bench_catalog_lookup are removed. They were ignored and only printed timings. - Checks over lists that can be empty now also check the count: reverse and move keep every stop, a conic draws its 4 wedges, each harmony gives at least two colors, the fit leaves patches out, the wireframe draws edges, a flat warp keeps its anchors, a gradient stroke has slices, and fitted dashes on a curve are drawn. - the_effects_are_colour_adjustments_in_their_own_menu checks one add-on effect and one effect outside it instead of every entry. --- crates/color/src/blend.rs | 8 +-- crates/color/src/cms/tests.rs | 51 ++++++++++-------- crates/color/src/cms/tests_icc.rs | 2 +- crates/color/src/cms/tests_measured.rs | 1 + crates/color/src/gradient/tests.rs | 5 +- crates/color/src/harmony.rs | 15 +++--- crates/color/src/libraries.rs | 12 ----- crates/color/src/recolor.rs | 8 +-- crates/color/src/swatch.rs | 23 ++++++--- crates/color/src/wcag.rs | 7 +-- crates/effects/src/addons/color.rs | 7 ++- crates/effects/src/pixel/tests.rs | 54 -------------------- crates/effects/src/solids/wireframe/tests.rs | 6 ++- crates/effects/src/stroke/tests_fit.rs | 1 + crates/effects/src/stroke/tests_gradient.rs | 4 +- crates/effects/src/tests.rs | 25 +++------ 16 files changed, 91 insertions(+), 138 deletions(-) diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index c4338c289e..d622332c32 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -313,8 +313,10 @@ mod tests { assert_eq!(BlendMode::parse("ColorBurn"), Some(BlendMode::ColorBurn)); assert_eq!(BlendMode::parse("soft_light"), Some(BlendMode::SoftLight)); assert_eq!(BlendMode::parse("nope"), None); - for m in BlendMode::ALL { - assert_eq!(BlendMode::parse(m.label()), Some(m)); - } + assert_eq!(BlendMode::parse(""), None); + // A label that starts another one names its own mode. + assert_eq!(BlendMode::parse("Color"), Some(BlendMode::Color)); + assert_eq!(BlendMode::parse("Color Dodge"), Some(BlendMode::ColorDodge)); + assert_eq!(BlendMode::parse("HARD-LIGHT"), Some(BlendMode::HardLight)); } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 761a121191..47131dc678 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -15,11 +15,14 @@ fn de(a: [f32; 3], b: [f32; 3]) -> f32 { #[test] fn intents_parse_and_name() { - for i in Intent::ALL { - assert_eq!(Intent::parse(i.id()), Some(i)); - assert_eq!(Intent::parse(i.label()), Some(i)); - } + // The id settings save and the label the menu shows both read back, in any case and spacing. + assert_eq!(Intent::RelativeColorimetric.id(), "relative"); + assert_eq!(Intent::parse("relative"), Some(Intent::RelativeColorimetric)); + assert_eq!(Intent::parse("Relative Colorimetric"), Some(Intent::RelativeColorimetric)); + assert_eq!(Intent::parse("absolute_colorimetric"), Some(Intent::AbsoluteColorimetric)); + assert_eq!(Intent::parse("PERCEPTUAL"), Some(Intent::Perceptual)); assert_eq!(Intent::parse("bogus"), None); + assert_eq!(Intent::parse(""), None); } #[test] @@ -322,21 +325,29 @@ fn bad_icc_rejected() { assert!(matches!(register_icc(b"not a profile", None), Err(CmsError::BadProfile(_)))); } -#[cfg(target_os = "macos")] +/// A profile file is read and registered as its bytes are: a missing file is an I/O error naming +/// the path, a file that is not a profile is refused as one, and a file holding a built-in +/// profile is refused for its name. +#[cfg(not(target_arch = "wasm32"))] #[test] -fn loads_system_cmyk_icc() { - let path = std::path::Path::new("/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"); - if !path.exists() { - return; +fn loads_icc_files_and_refuses_bad_ones() { + let dir = std::env::temp_dir().join(format!("vectorcraft-color-icc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let missing = dir.join("missing.icc"); + match load_icc_file(&missing) { + Err(CmsError::Io(e)) => assert!(e.contains("missing.icc"), "{e}"), + other => panic!("{other:?}"), } - let info = load_icc_file(path).unwrap(); - assert_eq!(info.kind, ProfileKind::Cmyk); - assert!(profiles().iter().any(|p| p.name == info.name && !p.builtin)); - let c = Cms::new(&ColorSettings { cmyk: info.name.clone(), ..Default::default() }).unwrap(); - let rgb = [0.7, 0.5, 0.4]; - let back = c.cmyk_to_srgb(c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric), false); - assert!(de(rgb, back) < 5.0, "{back:?}"); - assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]); + let junk = dir.join("junk.icc"); + std::fs::write(&junk, b"not a profile").unwrap(); + assert!(matches!(load_icc_file(&junk), Err(CmsError::BadProfile(_)))); + let builtin = dir.join("generic.icc"); + std::fs::write(&builtin, &*icc_bytes(GENERIC_CMYK).unwrap()).unwrap(); + match load_icc_file(&builtin) { + Err(CmsError::Unsupported(e)) => assert!(e.contains("built-in"), "{e}"), + other => panic!("{other:?}"), + } + std::fs::remove_dir_all(&dir).unwrap(); } /// With black-point compensation, sRGB black separates to the press's black point and that black @@ -568,10 +579,10 @@ fn a_document_gets_the_same_context_for_the_same_profiles() { /// settings saved before the policies existed read with the default policy. #[test] fn policies_parse_and_default_in_saved_settings() { - for p in Policy::CMYK { - assert_eq!(Policy::parse(p.id()), Some(p)); - } + assert_eq!(Policy::parse("preserveNumbers"), Some(Policy::PreserveNumbers)); + assert_eq!(Policy::parse("convert"), Some(Policy::Convert)); assert_eq!(Policy::parse("bogus"), None); + assert_eq!(Policy::parse("Preserve Numbers"), None, "only ids parse"); assert!(!Policy::RGB.contains(&Policy::PreserveNumbers)); let old: ColorSettings = serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap(); diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index 3506bcb856..8cefd7cfe5 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -395,5 +395,5 @@ fn cmyk_to_cmyk_compensates_the_black_point() { assert_ne!(convert(true), convert(false)); // White is untouched. let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap(); - assert!(white.iter().all(|v| *v < 0.01), "{white:?}"); + assert!(white.len() == 4 && white.iter().all(|v| *v < 0.01), "{white:?}"); } diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs index 7bf5735c7a..cd2e06a70e 100644 --- a/crates/color/src/cms/tests_measured.rs +++ b/crates/color/src/cms/tests_measured.rs @@ -108,6 +108,7 @@ fn the_fit_predicts_patches_it_left_out() { let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0); let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0); let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p)); + assert!(!left.is_empty(), "{}: nothing left out", c.reference); assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference); let kept: Vec<measured::Patch> = kept.into_iter().copied().collect(); let left: Vec<measured::Patch> = left.into_iter().copied().collect(); diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 4d5c84c01f..fd39d0b94e 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -184,6 +184,7 @@ fn reverse_mirrors_midpoints() { r.reverse(); let mids: Vec<f32> = r.stops.iter().map(|s| s.midpoint).collect(); let want: Vec<f32> = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect(); + assert_eq!(mids.len(), g.stops.len(), "reversing keeps every stop"); assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}"); for i in 0..=20 { let t = i as f32 / 20.0; @@ -291,6 +292,7 @@ fn remove_keeps_two() { fn move_reorders_and_tracks_index() { let g = g3(); let (v, i) = move_stop(&g.stops, 0, 0.8); + assert_eq!(v.len(), g.stops.len(), "moving keeps every stop"); assert_eq!(i, 1); assert_eq!(v[1].color.to_hex(), "#ffffff"); assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset)); @@ -1176,7 +1178,8 @@ fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() { assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}"); assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}"); let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false); - assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}"); + assert_eq!(wedges.len(), 4, "{g:?}"); + assert!(wedges.iter().all(|(pts, _)| pts.len() >= 3 && pts.iter().all(|p| p.is_finite())), "{g:?}: {wedges:?}"); } // A flat extent keeps the vector's direction and the sign of its aspect. let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) }; diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 58fcd886ee..75a5fdc2a5 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -177,20 +177,23 @@ mod tests { fn harmonies_keep_the_base_model() { let base = Color::cmyk(0.0, 1.0, 1.0, 0.0); for h in Harmony::ALL { - assert!(apply(h, base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", label(h)); + let colors = apply(h, base); + assert!(colors.len() >= 2 && colors.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}: {colors:?}", label(h)); } let Color::Cmyk { c, m, y, .. } = apply(Harmony::Complementary, base)[1] else { panic!("a CMYK complement") }; assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}"); let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default()); - assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. }))); + let cells: Vec<&Color> = g.grid.iter().flatten().collect(); + assert!(!cells.is_empty() && cells.iter().all(|c| matches!(c, Color::Gray { .. })), "{cells:?}"); } #[test] fn rules_parse_by_id_and_label() { - for h in Harmony::ALL { - assert_eq!(parse(h.id()), Some(h)); - assert_eq!(parse(label(h)), Some(h)); - } + // A label reads back as its rule, its spaces and case ignored, and so does an id. + assert_eq!(parse("Split Complementary"), Some(Harmony::SplitComplementary)); + assert_eq!(parse("high contrast 3"), Some(Harmony::HighContrast3)); + assert_eq!(parse("tetrad2"), Some(Harmony::Tetrad2)); + assert_eq!(parse(""), None); assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index b4197ca0ef..f7e482e567 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -825,16 +825,4 @@ mod tests { let [l, ..] = to_oklab(&stop("Violet Edge", 4)); assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}"); } - - #[test] - fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() { - for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) { - for s in builtin_library(b.id).unwrap().iter() { - if let Paint::Gradient(g) = &s.paint { - assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name); - assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name); - } - } - } - } } diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 05c386e405..c90257b9f1 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -796,12 +796,12 @@ mod tests { #[test] fn methods_parse_by_id_and_label() { - for m in Method::ALL { - assert_eq!(Method::parse(m.id()), Some(m)); - assert_eq!(Method::parse(m.label()), Some(m)); - } + assert_eq!(Method::parse("preserveTints"), Some(Method::PreserveTints)); + assert_eq!(Method::parse("Hue Shift"), Some(Method::HueShift)); + assert_eq!(Method::parse("Tints and Shades"), Some(Method::TintsShades)); assert_eq!(Method::parse("tints & shades"), Some(Method::TintsShades)); assert_eq!(Method::parse("nope"), None); + assert_eq!(Method::parse(""), None); } #[test] diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index 12ae31220a..b9ce45b1df 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -186,13 +186,20 @@ mod tests { #[test] fn default_swatches_parse() { - // `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure - // none falls back. - let src = include_str!("swatch.rs"); - let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect(); - assert!(hexes.len() > 30); - for h in hexes { - assert!(Color::from_hex(h).is_some(), "{h}"); - } + // `solid` and `grad` fall back to black or white on a bad hex literal. A fallback gives a + // solid the color of Black or White, and a gradient a stop that differs from the swatch + // its hex literal names. + let (s, g) = default_swatches(Model::Rgb); + let solids: Vec<Color> = s.iter().chain(g.iter().flat_map(|g| &g.swatches)).filter_map(|w| w.paint.color()).collect(); + assert!(solids.len() > 40, "{}", solids.len()); + let repeated: Vec<&Color> = solids.iter().enumerate().filter(|(i, c)| solids[..*i].contains(c)).map(|(_, c)| c).collect(); + assert_eq!(repeated, Vec::<&Color>::new(), "colors of more than one default swatch"); + let color = |name: &str| s.iter().find(|w| w.name == name).and_then(|w| w.paint.color()); + let stops = |name: &str| match s.iter().find(|w| w.name == name).map(|w| &w.paint) { + Some(Paint::Gradient(gp)) => gp.gradient.stops.iter().map(|st| Some(st.color)).collect::<Vec<_>>(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!(stops("Sunset"), [color("Amber"), color("Rose")]); + assert_eq!(stops("Ocean"), [color("Cyan"), color("Blue")]); } } diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index ba5bb3b974..9abb0d80ea 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -208,10 +208,11 @@ mod tests { #[test] fn category_ids_parse_back() { - for c in Category::ALL { - assert_eq!(Category::parse(c.id()), Some(c)); - } + // Commands and saved settings name a category by its id, exactly. + assert_eq!(Category::parse("largeText"), Some(Category::LargeText)); + assert_eq!(Category::parse("graphics"), Some(Category::Graphics)); assert_eq!(Category::parse("NormalText"), None); + assert_eq!(Category::parse("Large Text"), None, "a label is not an id"); } fn hue(srgb: [f32; 3]) -> f64 { diff --git a/crates/effects/src/addons/color.rs b/crates/effects/src/addons/color.rs index d6edf5f576..3cb72f60d4 100644 --- a/crates/effects/src/addons/color.rs +++ b/crates/effects/src/addons/color.rs @@ -109,10 +109,9 @@ mod tests { #[test] fn the_effects_are_colour_adjustments_in_their_own_menu() { - for id in EFFECTS { - assert!(crate::is_adjustment(id), "{id}"); - assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]); - } + assert!(crate::is_adjustment(DUOTONE)); + assert_eq!(crate::effect_info(DUOTONE).unwrap().menu, ["Effect", "Color Effects"]); + assert!(!crate::is_adjustment("stylize.dropShadow"), "an effect outside the add-on is not one"); } #[test] diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index b0c5332c29..f389c399e7 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -1065,60 +1065,6 @@ fn linear_light_blur_mixes_light_not_values() { } } -/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored -/// --nocapture pixel_timings`). -#[test] -#[ignore] -fn pixel_timings() { - let (w, h) = (2000, 2000); - let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]); - let s = PixelSpace { - to_doc: Affine::IDENTITY, - px: 1.0, - center: Point::new(1000.0, 1000.0), - size: vectorcraft_geom::Vec2::new(2000.0, 2000.0), - channels: Channels::Rgb, - line: 1.0, - extent: 0.0, - }; - let cases = [ - ("blur.radial", json!({"quality": "draft"})), - ("blur.radial", json!({"quality": "good"})), - ("blur.radial", json!({"quality": "best", "method": "zoom"})), - ("blur.smart", json!({"quality": "low"})), - ("blur.smart", json!({"quality": "high", "radius": 30})), - ("sharpen.unsharpMask", json!({"radius": 20})), - ("brushStrokes.accentedEdges", json!({"edgeWidth": 14})), - ("brushStrokes.angledStrokes", json!({"strokeLength": 50})), - ("brushStrokes.crosshatch", json!({"strokeLength": 50, "strength": 3})), - ("brushStrokes.darkStrokes", json!({})), - ("brushStrokes.inkOutlines", json!({"strokeLength": 50})), - ("brushStrokes.spatter", json!({"sprayRadius": 25})), - ("brushStrokes.sprayedStrokes", json!({"strokeLength": 20, "sprayRadius": 25})), - ("brushStrokes.sumiE", json!({"strokeWidth": 15})), - ("pixelate.colorHalftone", json!({"maxRadius": 4})), - ("pixelate.crystallize", json!({"cellSize": 3})), - ("pixelate.crystallize", json!({"cellSize": 300})), - ("pixelate.mezzotint", json!({"type": "grainyDots"})), - ("pixelate.pointillize", json!({"cellSize": 3})), - ("pixelate.pointillize", json!({"cellSize": 300})), - ("texture.craquelure", json!({"crackSpacing": 2})), - ("texture.craquelure", json!({"crackSpacing": 100})), - ("texture.grain", json!({"grainType": "clumped"})), - ("texture.mosaicTiles", json!({"tileSize": 2})), - ("texture.patchwork", json!({"squareSize": 0})), - ("texture.stainedGlass", json!({"cellSize": 2})), - ("texture.texturizer", json!({"texture": "sandstone", "scaling": 50})), - ("texture.texturizer", json!({"texture": "burlap"})), - ]; - for (id, p) in cases { - let mut d = src.clone(); - let t = std::time::Instant::now(); - fx(id, p.clone()).apply(&mut d, w, h, &s); - println!("{id} {p}: {:?}", t.elapsed()); - } -} - #[test] fn pixelate_params_take_defaults_and_stay_in_range() { assert_eq!(fx("pixelate.colorHalftone", json!({})), PixelFx::ColorHalftone { max_radius: 8.0, angles: [108.0, 162.0, 90.0, 45.0] }); diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index cb92d59e72..b20d0fedf0 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -466,14 +466,16 @@ fn wireframe_mode_is_checked_against_the_edges_it_draws() { assert!(refused.contains("simplify the gradient"), "{refused}"); assert_eq!(crate::validate_revolve(&n, &wire), Ok(())); n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap()); - assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some())); + let edges = leaves(&drawn(&n)); + assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len()); // On the fill. let fx = n.appearance.effects.remove(0); let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap(); assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err()); assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(())); n.appearance.items[at].effects_mut().push(fx); - assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some())); + let edges = leaves(&drawn(&n)); + assert!(!edges.is_empty() && edges.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{} pieces", edges.len()); } /// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before. diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index f7fecb9abc..343ef29c50 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -155,6 +155,7 @@ fn fitted_dashes_on_curves_and_degenerate_paths_stay_finite() { s.profile = profile.clone(); }); let o = line_outline(&mixed, &st, 4.0, 0.01); + assert!(!o.elements().is_empty(), "{pat:?}: the curve's dashes are drawn"); assert!(o.elements().iter().filter_map(|e| e.end_point()).all(|p| p.x.is_finite() && p.y.is_finite()), "{pat:?}"); } } diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index 55aeda8d7f..42a6723597 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -301,7 +301,9 @@ fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() { let mut st = stroke(10.0, mode); let g = Gradient { spread, repeats: 3, ..Gradient::default() }; st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone()))); - for s in slices(&bp, &st) { + let pieces = slices(&bp, &st); + assert!(!pieces.is_empty(), "{mode:?} {spread:?}: the stroke is painted in slices"); + for s in pieces { let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") }; let geom = p.geom.unwrap(); for u in [0.1, 0.5, 0.9] { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index aa77e45b2f..dadbd35ae8 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -247,15 +247,14 @@ fn a_warp_draws_with_the_map_its_version_names() { fn a_warp_bends_a_flat_box_as_the_middle_of_its_patch() { let anchors = |p: &PathData| p.subpaths.iter().flat_map(|s| s.anchors.clone()).collect::<Vec<_>>(); let vertical = shapes::line(Point::new(100.0, 0.0), Point::new(100.0, 100.0)); - let out = run("warp.arc", json!({"bend": 50, "version": 1}), &vertical); - assert!(anchors(&out).iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); + let out = anchors(&run("warp.arc", json!({"bend": 50, "version": 1}), &vertical)); + assert!(out.len() >= 2, "{out:?}"); + assert!(out.iter().all(|a| close(a.p.x, 100.0, 1e-9) && close(a.h_in.x, 100.0, 1e-9) && close(a.h_out.x, 100.0, 1e-9)), "{out:?}"); let horizontal = shapes::line(Point::new(0.0, 50.0), Point::new(200.0, 50.0)); for style in ["bulge", "fisheye", "inflate", "squeeze"] { - let out = run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal); - assert!( - anchors(&out).iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), - "{style}: {out:?}" - ); + let out = anchors(&run(&format!("warp.{style}"), json!({"bend": 50, "version": 1}), &horizontal)); + assert!(out.len() >= 2, "{style}: {out:?}"); + assert!(out.iter().all(|a| close(a.p.y, 50.0, 1e-9) && close(a.h_in.y, 50.0, 1e-9) && close(a.h_out.y, 50.0, 1e-9)), "{style}: {out:?}"); } } @@ -2084,18 +2083,6 @@ fn bad_params_fall_back_to_defaults() { assert!(close(out.bounds().unwrap().width(), 124.0, 0.1)); } -#[test] -#[ignore] -fn bench_catalog_lookup() { - let t = std::time::Instant::now(); - let mut n = 0; - for _ in 0..10_000 { - n += crate::is_geometry("distort.roughen") as usize; - n += crate::merged_params("stylize.dropShadow", &serde_json::Value::Null).as_object().unwrap().len(); - } - eprintln!("10k lookups: {:?} ({n})", t.elapsed()); -} - #[test] fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { use std::sync::Arc; From beeeacafe5f12337dae918cd151a403b9a2ecf89 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:25:24 -0800 Subject: [PATCH 62/71] Tests: text and doc tests check what the code returns, not only that it is there Tests in vectorcraft-text and vectorcraft-doc that could pass on an empty result, or that only checked a result exists, now assert the values: - Blend: gradient steps assert their stop count before checking each stop's swatch, tint and plates; the odd dash blended to solid asserts the whole pattern; a copied step asserts its members. - Symbols: limiting depth keeps every symbol; a stroke override on type keeps the run it styles. - File fonts: an extreme descent clamps to the lowest table value and the Windows descent still fits. - Invert wrap on a tangled shape asserts the line still meets it. - Bidi, ligature carets, Thai and whitespace fallback: the glyph and line counts are asserted, Hebrew points stay in their letters' clusters, and every character of an isolate test has a glyph. - Glyph categories, trace views, compound shape modes and digit systems check written-out ids instead of a round trip over every value. Removed joins_on_a_circle_are_measured, which printed measurements and asserted nothing, and chord_placement_leaves_the_join_gap_above_the_baseline, which checked arithmetic done in the test itself; joined_glyphs_meet_on_a_curved_path covers joined type on a curve. --- crates/doc/src/blend.rs | 20 +++++- crates/doc/src/compound_shape.rs | 9 ++- crates/doc/src/depth.rs | 1 + crates/doc/src/symbol_overrides.rs | 1 + crates/doc/src/text/tests.rs | 9 ++- crates/doc/src/trace.rs | 9 ++- crates/text/src/file_font.rs | 11 ++- crates/text/src/fontdb/gsub.rs | 8 ++- crates/text/src/layout/region.rs | 1 + crates/text/src/tests.rs | 3 + crates/text/src/tests/bidi.rs | 9 +++ crates/text/src/tests/ligature_carets.rs | 3 +- crates/text/src/tests/path_joins.rs | 86 +----------------------- crates/text/src/tests/sysfonts.rs | 1 + 14 files changed, 62 insertions(+), 109 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 2770471f70..7c40d9d133 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2784,10 +2784,13 @@ mod tests { Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))) }; let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); } @@ -2840,6 +2843,7 @@ mod tests { let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]); let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]); let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2848,6 +2852,7 @@ mod tests { // Without plates on either side the steps print the spot ink alone, as before. let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]); let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -2882,10 +2887,12 @@ mod tests { let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]); let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05])); // The ends keep their own plates. let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); // Another swatch, or an unlinked stop: process steps with no plates, as before. @@ -2897,6 +2904,7 @@ mod tests { let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]); for b in [&other, &plain] { let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } } @@ -2906,11 +2914,14 @@ mod tests { let p = [0.4, 0.8, 0.0, 0.2]; let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let Paint::Gradient(g) = &gradient else { panic!() }; - assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none())); + let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient); + assert_eq!(linked.stops.len(), 2); + assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops); let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 }; // The solid's end has no plates: they grow from none toward the gradient's, both ways round. for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] { let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2919,6 +2930,7 @@ mod tests { } // A process solid unlinks the steps, and they take no plates. let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -3401,7 +3413,8 @@ mod tests { #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); - assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern); + // Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it. + assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]); } #[test] @@ -3412,7 +3425,8 @@ mod tests { let mid = lerp_node(&a, &b, 0.4); let mut ids = vec![]; mid.walk(&mut |n| ids.push(n.id)); - assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}"); + // The step and its two members, all of them new. + assert_eq!(ids, [NodeId(0); 3]); } /// A blend of `a` and `b` spaced by `spacing`. diff --git a/crates/doc/src/compound_shape.rs b/crates/doc/src/compound_shape.rs index 3b36ff86dd..f3f4b83939 100644 --- a/crates/doc/src/compound_shape.rs +++ b/crates/doc/src/compound_shape.rs @@ -64,11 +64,10 @@ mod tests { #[test] fn modes_read_back_and_unknown_ones_are_add() { - for m in ShapeMode::ALL { - let v = serde_json::to_value(m).unwrap(); - assert_eq!(v, serde_json::json!(m.name())); - assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), m); - } + assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract")); + assert_eq!(serde_json::from_value::<ShapeMode>(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude); + assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect)); + assert_eq!(ShapeMode::parse("Intersect"), None); for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] { assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), ShapeMode::Add); } diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index c846dfc1c6..3872e16a54 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -613,6 +613,7 @@ mod tests { d.limit_depth_noting(&mut warnings); assert_eq!(warnings, [symbols_note()]); assert!(!d.too_deep(None), "{count} {last}"); + assert_eq!(d.symbols.len(), count, "every symbol is kept"); assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group"); } // An edit that makes one hold itself is seen, whatever else stayed as it was. diff --git a/crates/doc/src/symbol_overrides.rs b/crates/doc/src/symbol_overrides.rs index 241c61fba8..d9017815c7 100644 --- a/crates/doc/src/symbol_overrides.rs +++ b/crates/doc/src/symbol_overrides.rs @@ -253,6 +253,7 @@ mod tests { let mut a = Node::group(NodeId(1), vec![Arc::new(text)]); apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]); let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") }; + assert_eq!(t.runs.len(), 1); assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt"); // A path whose stroke has neither paint nor weight gets 1 pt too. diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 9371947565..607fa12238 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() { assert_eq!(map(d, "a-Z ٪"), "a-Z ٪"); } assert_eq!(map(Digits::Devanagari, "page 12"), "page १२"); - for d in Digits::ALL { - assert_eq!(serde_json::to_value(d).unwrap(), d.id()); - assert_eq!(serde_json::from_value::<Digits>(d.id().into()).unwrap(), d); - assert_eq!(Digits::from_id(d.id()), Some(d)); - } + assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari"); + assert_eq!(serde_json::from_value::<Digits>("farsi".into()).unwrap(), Digits::Farsi); + assert_eq!(Digits::Malayalam.id(), "malayalam"); + assert_eq!(Digits::from_id("default"), Some(Digits::Default)); assert_eq!(Digits::from_id("roman"), None); assert!(serde_json::from_value::<Digits>("roman".into()).is_err()); } diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index a2d17cc990..f462e18300 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -98,11 +98,10 @@ mod tests { #[test] fn ids_round_trip_and_unknown_views_show_the_result() { - for v in TraceView::ALL { - assert_eq!(TraceView::from_id(v.id()), Some(v)); - assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v)); - assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something"); - } + assert_eq!(TraceView::Source.id(), "sourceImage"); + assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource)); + assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter"); + assert_eq!(TraceView::from_id("tracing"), None); let mut g = Node::group(crate::NodeId(1), vec![]); assert_eq!(g.trace_view(), TraceView::Result); g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"}))); diff --git a/crates/text/src/file_font.rs b/crates/text/src/file_font.rs index 21215aa5f5..077bbae28d 100644 --- a/crates/text/src/file_font.rs +++ b/crates/text/src/file_font.rs @@ -456,7 +456,14 @@ mod tests { fn extreme_negative_descent_does_not_overflow() { let mut i = info(); i.descent = -100_000.0; - let bytes = build_file_font(&i, &glyphs("a")); - assert!(bytes.is_some()); + let bytes = build_file_font(&i, &glyphs("a")).unwrap(); + // The descent stops at the lowest value the tables hold, and the Windows descent, its + // magnitude, still fits. + let font = skrifa::FontRef::new(&bytes).unwrap(); + let metrics = font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + assert_eq!(metrics.descent, f32::from(i16::MIN)); + assert_eq!(metrics.ascent, 1760.0, "the ascent is the default 0.88 em"); + use skrifa::raw::TableProvider; + assert_eq!(font.os2().unwrap().us_win_descent(), 32_768); } } diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index 2fef163351..9c8daf19bf 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -687,9 +687,11 @@ mod tests { #[test] fn kinds_round_trip_through_their_ids() { - for kind in GlyphCategoryKind::all() { - assert_eq!(GlyphCategoryKind::from_id(&kind.id()), Some(kind)); - } + assert_eq!(GlyphCategoryKind::StylisticSet(3).id(), "ss03"); + assert_eq!(GlyphCategoryKind::from_id("ss03"), Some(GlyphCategoryKind::StylisticSet(3))); + assert_eq!(GlyphCategoryKind::from_id("ss3"), None); + assert_eq!(GlyphCategoryKind::from_id("stylisticAlternates"), Some(GlyphCategoryKind::StylisticAlternates)); + assert_eq!(GlyphCategoryKind::from_id("figures"), Some(GlyphCategoryKind::Figures)); assert_eq!(GlyphCategoryKind::StylisticSet(7).features(), [*b"ss07"]); assert_eq!(GlyphCategoryKind::StylisticSet(20).features(), [*b"ss20"]); assert_eq!(GlyphCategoryKind::from_id("ss21"), None); diff --git a/crates/text/src/layout/region.rs b/crates/text/src/layout/region.rs index f2a0f1bbfe..033e632d92 100644 --- a/crates/text/src/layout/region.rs +++ b/crates/text/src/layout/region.rs @@ -1696,6 +1696,7 @@ fn invert_wrap_with_an_offset_bounds_its_work_on_a_tangled_shape() { assert!(GROWN_BAND_WORK.get() <= 2 * MAX_INVERT_WRAP_WORK, "{} steps", GROWN_BAND_WORK.get()); let contour: Vec<(f64, f64)> = star.iter().map(|p| (p.x, p.y)).collect(); let spans = invert_wrap_spans(&contour, 1.0, 10.0, 90.0); + assert!(!spans.is_empty(), "the line still meets the shape"); assert!(spans.iter().all(|&(a, b)| a >= 4.0 && b <= 96.0), "{spans:?}"); let square = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)]; assert_spans(&invert_wrap_spans(&square, f64::NAN, 45.0, 55.0), &invert_wrap_spans(&square, 0.0, 45.0, 55.0)); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 40b29331f9..eb81d3c096 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1028,6 +1028,7 @@ fn whitespace_the_primary_font_lacks_takes_the_fallback_face() { assert!((width - 60.0).abs() < 0.01, "あ あ sets at 3 em: {:?}", l.glyphs.iter().map(|g| g.advance).collect::<Vec<_>>()); assert_ne!(l.glyphs[1].font_id, primary.id()); let l = layout(db(), &point("a\tb", style(20.0))); + assert_eq!(l.glyphs.len(), 3, "{:?}", l.glyphs); assert!(l.glyphs.iter().all(|g| g.font_id == primary.id())); } @@ -2649,6 +2650,8 @@ fn thai_loanwords_stay_whole() { let lines: Vec<&str> = l.lines.iter().map(|ln| &text[ln.start..ln.end]).collect(); // No line ends inside the word, whatever the Thai font's widths put beside it. let word = text.find("โปรแกรม").unwrap(); + assert!(lines.len() > 1, "70 pt wraps the sentence: {lines:?}"); + assert!(lines.iter().any(|ln| ln.contains("โปรแกรม")), "one line holds the word: {lines:?}"); assert!(l.lines.iter().all(|ln| ln.end <= word || ln.end >= word + "โปรแกรม".len()), "{lines:?}"); } diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index a8f035aa6e..4a761dda20 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -254,6 +254,9 @@ fn paragraph_direction_is_independent_and_neutrals_do_not_force_ltr() { fn hebrew_marks_stay_with_base_clusters() { let s = "שָׁלוֹם"; let l = text_layout(s); + // Each glyph's source starts at one of the four letters, never at a point after one. + let starts: std::collections::BTreeSet<usize> = l.glyphs.iter().map(|g| g.byte).collect(); + assert_eq!(starts, [0, 6, 8, 12].into(), "{:?}", l.glyphs.iter().map(|g| (g.byte, g.len)).collect::<Vec<_>>()); for g in &l.glyphs { assert!(s.get(g.byte..g.byte + g.len).is_some()); } @@ -413,6 +416,10 @@ fn bidi_isolates_numbers_and_brackets_keep_valid_clusters() { for g in &l.glyphs { assert!(s.get(g.byte..g.byte + g.len).is_some()); } + // Every character but the isolate marks is drawn by a glyph whose source holds it. + for (i, c) in s.char_indices().filter(|&(_, c)| !matches!(c, '\u{2067}' | '\u{2069}')) { + assert!(l.glyphs.iter().any(|g| (g.byte..g.byte + g.len).contains(&i)), "{s}: {c:?} at {i} has no glyph"); + } assert!(!selection_quads(&l, 0, s.len()).is_empty()); } } @@ -432,6 +439,7 @@ fn right_aligned_wrapped_rtl_keeps_trailing_spaces_outside_content() { #[test] fn visual_arrows_cross_rtl_paragraph_boundaries() { let l = text_layout("שלום\nעולם"); + assert_eq!(l.lines.len(), 2); assert!(l.lines.iter().all(|l| l.rtl)); assert_eq!(caret_horizontal(&l, 8, false), 9); assert_eq!(caret_horizontal(&l, 9, true), 8); @@ -492,6 +500,7 @@ fn paragraph_direction_overrides_the_first_strong_character() { #[test] fn left_to_right_text_is_untouched() { let l = text_layout("Plain text, 123 (and more)."); + assert_eq!((l.glyphs.len(), l.lines.len()), ("Plain text, 123 (and more).".len(), 1)); assert!(l.glyphs.iter().all(|g| !g.rtl) && l.lines.iter().all(|l| !l.rtl)); let bytes: Vec<_> = l.glyphs.iter().map(|g| g.byte).collect(); assert!(bytes.windows(2).all(|w| w[0] < w[1])); diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index 9189bc2f0b..392c1295a6 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -529,7 +529,8 @@ fn manual_kerning_moves_a_right_to_left_ligature_stop_with_the_glyph() { fn a_letter_and_its_mark_has_no_inner_stop() { let db = FontDb::with_font_dirs(vec![]); let l = layout(&db, &point("e\u{0301}", "Source Sans 3")); - assert!(l.glyphs.iter().all(|g| g.carets.is_empty()), "{:?}", l.glyphs); + assert!(!l.glyphs.is_empty()); + assert!(l.glyphs.iter().all(|g| (g.byte, g.len) == (0, 3) && g.carets.is_empty()), "{:?}", l.glyphs); } /// On a path, a click on either half of the ligature goes to its nearer stop, and the selection of diff --git a/crates/text/src/tests/path_joins.rs b/crates/text/src/tests/path_joins.rs index 1ac96e3f0f..467b107b9d 100644 --- a/crates/text/src/tests/path_joins.rs +++ b/crates/text/src/tests/path_joins.rs @@ -3,7 +3,7 @@ //! stroke, is the measure. Fonts are installed ones (none is kept in the repository): the tests //! that need an Arabic font say so and stop without one. use crate::*; -use kurbo::{Affine, BezPath, Point, Shape}; +use kurbo::{BezPath, Point, Shape}; use std::sync::Arc; use vectorcraft_doc::{CharStyle, TextKind}; @@ -20,90 +20,6 @@ fn circle(r: f64) -> vectorcraft_geom::PathData { vectorcraft_geom::PathData::from_bezpath(&kurbo::Circle::new((0.0, 0.0), r).to_path(1e-3)) } -/// Type `s` in `style` on a circle of radius `r`, the whole loop for it. -fn on_circle(s: &str, style: CharStyle, r: f64) -> TextLayout { - let mut t = TextObject::point(Point::ZERO, s, style); - t.kind = TextKind::OnPath { path: circle(r), start: 0.25, end: None }; - layout(FontDb::global(), &t) -} - -/// For each pair of neighbouring glyphs on the line (in visual order, inside a word), how far -/// apart the right edge of the left one and the left edge of the right one are, at the baseline -/// and `h` above it. -fn gaps(l: &TextLayout, text: &str, h: f64) -> Vec<(f64, f64)> { - // Visual order: the glyphs as placed, sorted along the line by where their left edge is on it. - let edges: Vec<(Point, Point, Point, Point, usize)> = l - .glyphs - .iter() - .filter(|g| text.get(g.byte..g.byte + g.len).is_some_and(|c| !c.trim().is_empty())) - .map(|g| { - let [a, b, ..] = g.xf.as_coeffs(); - let sx = a.hypot(b); - let w = g.advance / sx; - let up = h / sx; - (g.xf * Point::new(0.0, 0.0), g.xf * Point::new(w, 0.0), g.xf * Point::new(0.0, -up), g.xf * Point::new(w, -up), g.byte) - }) - .collect(); - // Which word a byte is in: the spaces before it. - let word = |b: usize| text.get(..b).map_or(0, |t| t.chars().filter(|c| c.is_whitespace()).count()); - edges.windows(2).filter(|w| word(w[0].4) == word(w[1].4)).map(|w| ((w[0].1 - w[1].0).hypot(), (w[0].3 - w[1].2).hypot())).collect() -} - -/// The largest gaps (baseline, joining height) of type `s` on a circle of radius `r` at `size`. -fn worst(face: &FontFace, s: &str, size: f64, r: f64) -> (f64, f64) { - let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size, ..CharStyle::default() }; - let l = on_circle(s, style, r); - gaps(&l, s, size * 0.25).into_iter().fold((0.0, 0.0), |(a, b), (x, y)| (f64::max(a, x), f64::max(b, y))) -} - -/// The measure, printed: joined Arabic and separate Latin on circles at three sizes. -#[test] -fn joins_on_a_circle_are_measured() { - let Some(face) = arabic_face() else { - eprintln!("SKIPPED: joins_on_a_circle_are_measured; no installed font covers Arabic"); - return; - }; - eprintln!("ASSERTIONS RUN: joins_on_a_circle_are_measured; Arabic font {} {}", face.family, face.style); - for size in [12.0, 29.0, 72.0] { - for r in [60.0, 110.0, 300.0] { - let (b, j) = worst(&face, "سلسلة متصلة", size, r); - let (lb, lj) = worst(&face, "minimum", size, r); - eprintln!("size {size:>4} r {r:>5}: arabic baseline {b:.4} join {j:.4} | latin baseline {lb:.4} at {lj:.4}"); - } - } - let _ = BezPath::new(); - let _ = Affine::IDENTITY; -} - -/// Chord placement, worked out here only (not in the layout): each glyph's baseline ends on the -/// circle, the glyph turned to the chord between them. Neighbours then meet at the baseline, and `h` -/// above it they stand apart by `h` times the angle between their chords, (a_i + a_{i+1}) / 2R. -#[test] -fn chord_placement_leaves_the_join_gap_above_the_baseline() { - let Some(face) = arabic_face() else { - eprintln!("SKIPPED: chord_placement_leaves_the_join_gap_above_the_baseline; no installed font covers Arabic"); - return; - }; - let (size, r) = (29.0, 110.0); - let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size, ..CharStyle::default() }; - let s = "سلسلة"; - let l = on_circle(s, style, r); - let h = size * 0.25; - let advances: Vec<f64> = l.glyphs.iter().map(|g| g.advance).filter(|a| *a > 1e-6).collect(); - let mut worst: f64 = 0.0; - for w in advances.windows(2) { - let (a, b) = (w[0], w[1]); - // The chords' directions differ by the angle between their middles on the circle. - let turn = (a + b) / (2.0 * r); - let gap = 2.0 * h * (turn * 0.5).sin(); - let predicted = h * (a + b) / (2.0 * r); - assert!((gap - predicted).abs() < 0.01, "{gap} vs {predicted}"); - worst = worst.max(gap); - } - eprintln!("chord placement at {size} pt on radius {r}: baseline gap 0, join-height gap {worst:.3}"); - assert!(worst > 0.5, "chord placement alone leaves a visible gap: {worst}"); -} - /// A circle of radius `r` run the other way (clockwise): type on it stands on the inside, its /// tops towards the centre, as Flip puts it. fn circle_reversed(r: f64) -> vectorcraft_geom::PathData { diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 246f589518..66ae287023 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -1151,6 +1151,7 @@ fn thai_falls_back_to_a_font_made_for_thai() { let l = layout(db, &TextObject::point(kurbo::Point::ZERO, "Thai ภาษาไทย", st)); let family = |g: &PositionedGlyph| db.face_by_id(g.font_id).map(|f| f.family.clone()).unwrap_or_default(); let (latin, thai_glyphs) = l.glyphs.split_at(5); + assert_eq!(thai_glyphs.len(), "ภาษาไทย".chars().count(), "a glyph for each Thai letter"); assert!(latin.iter().all(|g| family(g) == FALLBACK_FAMILY), "{:?}", latin.iter().map(family).collect::<Vec<_>>()); let first = crate::fontdb::THAI_FAMILIES.iter().find(|f| thai_glyphs.iter().all(|g| family(g).eq_ignore_ascii_case(f))); assert!(first.is_some(), "Thai drawn in {:?}; {thai} is installed", thai_glyphs.iter().map(family).collect::<Vec<_>>()); From f0dbad051c6778818ed916ea618fbc1a0276ee56 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:25:41 -0800 Subject: [PATCH 63/71] Tests: render and trace tests check what they claim Weak tests in vectorcraft-render and vectorcraft-trace now assert the behavior they name: - The stroke glow test checks that the glow is drawn and that four threads draw what one does, instead of only rendering. - The JPEG and palette id tests name saved ids and labels directly (gray, optimized, none, blackWhite), unknown and empty ids, instead of looping over every value and reading its own id back. - The trace presets test drops the loop over every preset name, which presets().len() already covers, and checks the [Default] and padded name lookups by their result. - Nested discs each get the disc below them as parent, checked exactly. - A 20 degree bend gets no corner under a 30 degree minimum turn, and gets one under a 10 degree minimum. - The gray BMP, reduced CMYK and tiled image tests check the size of what they read, and the long stroke tests check that one outline was made before checking that none is cropped. - The three drag timing probes assert that the frame after the drag is what a fresh renderer draws, in place of printing two hashes. --- crates/render/src/encode/tests_bmp.rs | 1 + crates/render/src/encode/tests_jpeg.rs | 17 ++++++----- crates/render/src/encode/tests_palette.rs | 17 +++++++---- crates/render/src/fx/tests.rs | 36 ++++++++++++----------- crates/render/src/tests/longstroke.rs | 14 +++++++-- crates/render/src/tests/memory.rs | 2 ++ crates/render/src/tests/viewraster.rs | 14 ++------- crates/trace/src/group.rs | 4 ++- crates/trace/src/logo/restore.rs | 8 ++++- crates/trace/src/tests.rs | 7 ++--- 10 files changed, 70 insertions(+), 50 deletions(-) diff --git a/crates/render/src/encode/tests_bmp.rs b/crates/render/src/encode/tests_bmp.rs index f458c1999b..64d3ecdb55 100644 --- a/crates/render/src/encode/tests_bmp.rs +++ b/crates/render/src/encode/tests_bmp.rs @@ -133,6 +133,7 @@ fn greys_and_impossible_combinations() { let px = art(w, h); for depth in [8, 24] { let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), craft_image_codecs::Format::Bmp); + assert_eq!(img.dimensions(), (w, h), "depth {depth}"); assert!(img.pixels().all(|p| p[0] == p[1] && p[1] == p[2]), "depth {depth}: greys"); } let bad = [ diff --git a/crates/render/src/encode/tests_jpeg.rs b/crates/render/src/encode/tests_jpeg.rs index 413781de13..375dcaf15a 100644 --- a/crates/render/src/encode/tests_jpeg.rs +++ b/crates/render/src/encode/tests_jpeg.rs @@ -164,15 +164,18 @@ fn colour_models_write_their_components_and_profiles() { #[test] fn model_and_method_ids_round_trip() { - for m in ColorModel::ALL { - assert_eq!(ColorModel::from_id(m.id()), Some(m)); - assert_eq!(ColorModel::from_id(m.label()), Some(m)); - } + // Saved options name a model or a method by id or label, in any case. + assert_eq!(ColorModel::from_id("cmyk"), Some(ColorModel::Cmyk)); + assert_eq!(ColorModel::from_id("RGB"), Some(ColorModel::Rgb)); + assert_eq!(ColorModel::from_id("gray"), Some(ColorModel::Gray)); + assert_eq!(ColorModel::from_id("Grayscale"), Some(ColorModel::Gray)); assert_eq!(ColorModel::from_id("grey"), Some(ColorModel::Gray)); - for m in Method::ALL { - assert_eq!(Method::from_id(m.id()), Some(m)); - } + assert_eq!(ColorModel::from_id("lab"), None); + assert_eq!(Method::from_id("optimized"), Some(Method::Optimized)); + assert_eq!(Method::from_id("baseline optimized"), Some(Method::Optimized)); + assert_eq!(Method::from_id("Progressive"), Some(Method::Progressive)); assert_eq!(Method::from_id("bogus"), None); + assert_eq!(Method::from_id(""), None); } /// A 20×10 pt document: a black-ink rectangle on the left half, an RGB red one on the right. diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 837c62f359..d4067fc743 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -245,12 +245,17 @@ fn gif_decodes() { #[test] fn ids_round_trip() { - for r in Reduction::ALL { - assert_eq!(Reduction::from_id(r.id()), Some(r)); - } - for d in Dither::ALL { - assert_eq!(Dither::from_id(d.id()), Some(d)); - } + // Saved options name a reduction or a dither by id or label, in any case. + assert_eq!(Reduction::from_id("blackWhite"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("blackwhite"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("Black & White"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("selective"), Some(Reduction::Selective)); + assert_eq!(Reduction::from_id("restrictive"), None); + assert_eq!(Dither::from_id("none"), Some(Dither::None)); + assert_eq!(Dither::from_id("No Dither"), Some(Dither::None)); + assert_eq!(Dither::from_id("PATTERN"), Some(Dither::Pattern)); + assert_eq!(Dither::from_id("bayer"), None); + assert_eq!(Dither::from_id(""), None); } /// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 757290ed1f..f843ce01f7 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -371,9 +371,16 @@ fn per_stroke_raster_effects_use_the_single_threaded_pipeline() { } d.remove(id).unwrap(); d.insert(Some(l), 0, n).unwrap(); - let mut r = Renderer::new(); - r.threads = 4; - let _ = r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + let draw = |threads| { + let mut r = Renderer::new(); + r.threads = threads; + r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()) + }; + let (threaded, single) = (draw(4), draw(1)); + // The stroke's glow shows outside it: red, where nothing else is drawn. + let glow = threaded.pixel(40, 14); + assert!(glow[3] > 0 && glow[0] > glow[1] && glow[0] > glow[2], "{glow:?}"); + assert!(threaded.pixels == single.pixels, "four threads draw what one does"); } #[test] @@ -1966,7 +1973,7 @@ fn rasters_made_over_moved_rasters_count_as_moved() { /// Reproduce #1257's moving, filtered rectangle: the first frame renders as before a drag, /// and the next eight render as the canvas renders a drag's frames (`interacting`). Then the /// eighth position renders as the canvas renders the frame after the drag, and that frame -/// renders once more with every raster cached. +/// renders once more with every raster cached. Both draw what a fresh renderer draws. /// Run with `cargo test -p vectorcraft-render texture_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] @@ -2004,10 +2011,12 @@ fn texture_drag_perf() { } let mut time = |o: &RenderOptions| { let start = std::time::Instant::now(); - std::hint::black_box(r.render(&doc, 1800, 1500, view, o)); - start.elapsed().as_secs_f64() * 1000.0 + let image = r.render(&doc, 1800, 1500, view, o); + (start.elapsed().as_secs_f64() * 1000.0, image.pixels) }; - let (after, again) = (time(&opts), time(&opts)); + let ((after, after_px), (again, again_px)) = (time(&opts), time(&opts)); + let fresh = Renderer::new().render(&doc, 1800, 1500, view, &opts).pixels; + assert!(after_px == fresh && again_px == fresh, "{effect}: the frame after the drag draws what a fresh renderer draws"); ms.sort_by(f64::total_cmp); println!( "{effect}: moved CMYK rounded rectangle at 190.07%, DPI 1.5, 1800x1500: median {:.2} ms; samples {ms:?}; the frame after the drag {after:.2} ms, that frame again {again:.2} ms", @@ -2020,7 +2029,7 @@ fn texture_drag_perf() { /// view centered on the rectangle: the first frame renders as before a drag, and the next eight /// render as a drag's frames, once with `interacting` alone and once with `dragging` as well (as /// the canvas renders them). Then the eighth position renders as the canvas renders the frame -/// after the drag. The hashes of that frame and of a fresh renderer's frame compare builds. +/// after the drag, which draws what a fresh renderer draws. /// Run with `cargo test -p vectorcraft-render zoomed_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] @@ -2030,12 +2039,6 @@ fn zoomed_drag_perf() { ("Gaussian Blur 8 pt", vec![("blur.gaussian", json!({"radius": 8}))]), ("Drop Shadow and Craquelure", vec![("stylize.dropShadow", json!({"blur": 7})), ("texture.craquelure", json!({}))]), ]; - let hash = |px: &[u8]| { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - px.hash(&mut h); - h.finish() - }; for (name, effects) in sets { for zoom in [1.0, 4.0, 16.0, 64.0] { let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), effects.clone()); @@ -2062,15 +2065,14 @@ fn zoomed_drag_perf() { let still = r.render(&doc, 2560, 1440, view, &opts); let after = start.elapsed().as_secs_f64() * 1000.0; let fresh = Renderer::new().render(&doc, 2560, 1440, view, &opts); + assert!(still.pixels == fresh.pixels, "{name} at {zoom}x, dragging {dragging}: the frame after the drag"); ms.sort_by(f64::total_cmp); println!( - "{name} at {:.0}%, dragging {dragging}: drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + "{name} at {:.0}%, dragging {dragging}: drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms", zoom * 100.0, (ms[3] + ms[4]) * 0.5, ms[0], ms[7], - hash(&still.pixels), - hash(&fresh.pixels) ); } } diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index a69ac094ae..28adeba7c2 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -275,12 +275,19 @@ fn short_dashed_strokes_are_outlined_whole() { let one = BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(100.0, 100.0))]); let mut dot = one.clone(); dot.line_to((100.0, 100.0)); - for (what, bp) in - [("empty", BezPath::new()), ("one anchor", one), ("one anchor, closed on itself", dot), ("a ring of 40 anchors", ring(40, 80.0))] - { + // The ring is outlined once; the degenerate paths only have to draw what a whole outline draws. + for (what, bp, ring_of_40) in [ + ("empty", BezPath::new(), false), + ("one anchor", one, false), + ("one anchor, closed on itself", dot, false), + ("a ring of 40 anchors", ring(40, 80.0), true), + ] { let d = doc(&bp, st.clone()); let mut r = Renderer::new(); let img = render(&mut r, &d, Point::new(100.0, 100.0)); + if ring_of_40 { + assert_eq!(r.strokes.len(), 1, "{what}: one outline"); + } assert!(r.strokes.values().all(|e| e.crop.is_none()), "{what}: outlined whole"); assert!(img.pixels == whole(&d, Point::new(100.0, 100.0)).pixels, "{what}: the same pixels"); } @@ -393,6 +400,7 @@ fn a_stroke_a_wide_stroke_crosses_over_stays_whole() { let at = Point::new(20_000.0, 2.0); let mut r = Renderer::new(); let img = render(&mut r, &d, at); + assert_eq!(r.strokes.len(), 1, "one outline"); assert!(r.strokes.values().all(|e| e.crop.is_none())); assert!(img.pixels == whole(&d, at).pixels); } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index d5009c2072..8579c314b8 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2662,6 +2662,7 @@ fn a_reduced_cmyk_image_paints_its_own_inks() { let d = cmyk_doc_with("inks", blob, 8, 8); let on = RenderOptions { image_mips: true, ..Default::default() }; let inks = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 8.0, 8.0), 0.25, &on); + assert_eq!(inks.len(), 2 * 2 * 4, "2 × 2 pixels of four inks"); for px in inks.as_chunks::<4>().0 { assert!(px.iter().zip(ink).all(|(a, b)| a.abs_diff(b) <= 1), "{px:?} vs {ink:?}"); } @@ -2805,6 +2806,7 @@ fn a_tiled_image_draws_what_the_whole_image_draws() { let plane = |ink| ink::ink_image(&key, &full, ink, d.images.get("seams"), false).1; let bytes = |pm: &Pixmap| pm.data().iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect::<Vec<u8>>(); let whole = ink::amounts(&bytes(&plane(Ink::Cmy)), &bytes(&plane(Ink::K))); + assert_eq!(drawn.len(), 300 * 40 * 4, "300 × 40 pixels of four inks"); for (i, got) in drawn.as_chunks::<4>().0.iter().enumerate() { let (x, y) = (x0 as usize + i % 300, i / 300); let want = &whole[(y * w as usize + x) * 4..][..4]; diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 0087c1a4a8..0a69d9ba3c 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -420,18 +420,11 @@ fn a_shadow_over_a_cropped_shadow_keeps_to_the_earlier_ones_margin() { /// Time a drag of the square over each backdrop in a 2560 × 1440 view: the first frame renders as /// before a drag, the next eight as a drag's frames (`interacting` and `dragging`, as the canvas -/// renders them), then the frame after the drag. The hashes of that frame and of a fresh renderer's -/// frame compare builds. +/// renders them), then the frame after the drag, which draws what a fresh renderer draws. /// Run with `cargo test --release -p vectorcraft-render backdrop_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] fn backdrop_drag_perf() { - let hash = |px: &[u8]| { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - px.hash(&mut h); - h.finish() - }; let size = (2560, 1440); for (name, effects, zoom) in cases() { let (base, id) = backdrop(&effects); @@ -455,15 +448,14 @@ fn backdrop_drag_perf() { let still = r.render(&doc, size.0, size.1, xf, &opts); let after = start.elapsed().as_secs_f64() * 1000.0; let fresh = Renderer::new().render(&doc, size.0, size.1, xf, &opts); + assert!(still.pixels == fresh.pixels, "{name} at {zoom}x: the frame after the drag"); ms.sort_by(f64::total_cmp); println!( - "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms", zoom * 100.0, (ms[3] + ms[4]) * 0.5, ms[0], ms[7], - hash(&still.pixels), - hash(&fresh.pixels) ); } } diff --git a/crates/trace/src/group.rs b/crates/trace/src/group.rs index a0e3b85020..1050166631 100644 --- a/crates/trace/src/group.rs +++ b/crates/trace/src/group.rs @@ -451,7 +451,9 @@ mod tests { let want = parents_by_pairs(&paths, 200, 200, stacked); let pairs = BOX_TESTS.with(std::cell::Cell::get); assert_eq!(found, want, "stacked {stacked}"); - assert!(want.iter().skip(1).all(Option::is_some), "stacked {stacked}: {want:?}"); + // Each disc lies inside the one below it, the smallest that holds it. + let chain: Vec<Option<usize>> = (0..paths.len()).map(|i| i.checked_sub(1)).collect(); + assert_eq!(want, chain, "stacked {stacked}"); assert!(tests <= pairs, "stacked {stacked}: {tests} box tests, {pairs} by pairs"); } } diff --git a/crates/trace/src/logo/restore.rs b/crates/trace/src/logo/restore.rs index 984a073f64..908d98923d 100644 --- a/crates/trace/src/logo/restore.rs +++ b/crates/trace/src/logo/restore.rs @@ -189,7 +189,13 @@ mod tests { } let (r, step) = resample_closed(&pts, 0.12).expect("resample"); let s0 = smooth_closed(&r, 0.18 / step); - let _ = restore_corners(&r, &s0, step, &RestoreParams { min_turn: 30.0, ..RestoreParams::default() }); + // The bend at (20, 0) is a candidate (turn 10), and only the minimum turn decides it. + let bend = |min_turn: f64| { + let (out, forced) = restore_corners(&r, &s0, step, &RestoreParams { turn: 10.0, min_turn, ..RestoreParams::default() }); + forced.iter().map(|&i| out[i].distance(Point::new(20.0, 0.0))).fold(f64::MAX, f64::min) + }; + assert!(bend(30.0) > 1.0, "a 20 degree bend under a 30 degree minimum: {} px from a corner", bend(30.0)); + assert!(bend(10.0) < 0.1, "under a 10 degree minimum it is one: {} px off", bend(10.0)); } #[test] diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 3fd5c2000b..a461978600 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -912,11 +912,10 @@ fn snap_curves_to_lines_straightens_near_lines() { #[test] fn presets_resolve() { + // Every name resolves: `presets` leaves out a name `preset` does not know. assert_eq!(presets().len(), 15); - for n in PRESET_NAMES { - assert!(preset(n).is_some(), "{n}"); - } - assert!(preset("[Default]").is_some()); + assert_eq!(preset("[Default]"), preset("Default")); + assert_eq!(preset(" Line Art "), preset("line art")); assert_eq!(preset("16 colors").unwrap().colors, 16); assert_eq!(preset("Shades of Gray").unwrap().mode, Mode::Grayscale); assert_eq!(preset("flat logo").unwrap().mode, Mode::Logo); From 5b2b29c73f74b195dc36bd9af044723e5e5f4c71 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:28:06 -0800 Subject: [PATCH 64/71] Properties: an edit made during a drag is measured when the drag ends A scrubbed field or a canvas drag moves the revision while the sections are not measured. When the release itself left the revision unchanged, the panel skipped the measurement and kept the sizes from before the drag. The edit now stays pending until a frame runs without a drag or an open undo group. --- crates/ui-egui/src/panels/properties.rs | 9 ++++- crates/ui-egui/src/panels/properties/tests.rs | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 6194f28085..06d19cd822 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -31,6 +31,8 @@ pub struct PropertiesUi { content: Option<u64>, /// The document (uid, revision) the sections were last shown for. revision: Option<(u64, u64)>, + /// An edit made during a drag whose sections are not measured yet. + measure_pending: bool, } /// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -72,9 +74,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let content_changed = app.ui.properties_panel.content.replace(content) != Some(content); let edited = std::mem::replace(&mut app.ui.properties_panel.revision, revision) != revision; // A drag on the canvas, or a scrubbed field, moves the revision on every pointer move without changing which - // sections show: the sections are measured again for an edit once the drag ends, not on each move. + // sections show: the sections are measured again for an edit once the drag ends, not on each move. The edit stays + // pending until then, also when the release itself does not move the revision. let dragging = app.session.active().is_some_and(|st| st.interaction.is_some() || st.undo_group.is_some()); - let changed = content_changed || (edited && !dragging); + let pending = app.ui.properties_panel.measure_pending || edited; + let changed = content_changed || (pending && !dragging); + app.ui.properties_panel.measure_pending = pending && !changed; let mut sections = |ui: &mut Ui, _: &mut BodyCx<'_>| { // The reference panel's labels end in a colon beside fields that keep their own width. Stack::new().fill_width().labels(LabelScheme::Form).show(ui, |ui, _| { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index c46bcbf6e4..dea62a6dfa 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -241,6 +241,43 @@ fn a_drag_does_not_measure_the_sections_on_each_move() { assert_eq!(frame(&mut app, vec![]).1, 1, "an edit without a drag measures the sections"); } +/// An edit made while an undo group is open, as a scrubbed field's drag makes, is measured once the group ends, also +/// when ending it does not move the document's revision. +#[test] +fn an_edit_during_a_drag_is_measured_when_the_drag_ends_without_a_new_revision() { + let measures = || SECTION_MEASURES.with(std::cell::Cell::get); + let mut app = new_app(); + let a = rect(&mut app, 100.0, 100.0, 80.0, 80.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let measured = measures(); + let _ = crate::testing::app_frame(app, &ctx, raw); + measures() - measured + }; + for _ in 0..4 { + frame(&mut app); + } + app.run("edit.undoGroup.begin", json!({})).unwrap(); + assert_eq!(frame(&mut app), 0, "opening the group"); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(frame(&mut app), 0, "an edit inside the group"); + let revision = app.session.active().unwrap().revision; + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().revision, revision, "ending the group keeps the revision"); + assert_eq!(frame(&mut app), 1, "the end of the group measures the edit"); + assert_eq!(frame(&mut app), 0, "a settled frame"); +} + /// Start Global Edit in Quick Actions starts it on the one selected path, the button then reads /// Stop Global Edit, and Escape stops it. Selected type has no Start Global Edit button. #[test] From ccf57654197452f0eed5044b3e58f60016938865 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:35:21 -0800 Subject: [PATCH 65/71] Tests: assert counts and saved names in tool, path, 3D, brush and CAD tests Tests whose all() passed on an empty list now check the list's length or that it is not empty: - huge_circles_bridge_with_finite_anchors_or_are_refused (pathops bridge) - smooth_rounds_corners (pathops ops): the four corners stay, smoothed - a_held_rotation_turns_the_art_around_its_pin (tools ARAP): one point per mesh vertex - the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_during_the_drag (tools gesture): one released point per press - every_effect_casts_a_shadow, inflate_cells_across_a_hole_edge_are_cut_to_the_shape, a_plane_has_only_a_front_and_a_hollow_solid_none and perspective_runs_0_to_160_degrees_with_the_eye_outside_the_object (three-d) - a_file_two_branches_include_is_followed_from_the_shallower_one (scriptcheck): one row per include line - pens_pick_colors_and_widths (cad HP-GL): four widths - junk_pressure_brushes_draw_finite_art (brush): all 12 cases draw Round trips that hold by construction (parse finds the id in ALL) are replaced with one saved name that must parse and one that must not: follow_names_parse (pathops shared edge), the shape kinds (pathops shapes), surfaces_parse_from_their_ids (three-d), the Quick Pen actions (tools), names_parse_and_serialize_as_names (plugins) and the brush variation modes, which also compare the serde names with the ids. crop_keeps_an_instance_whose_art_reaches_the_region (cad) names the entities written instead of checking that some were. the_saved_engine_preference_is_found (app) pins the GPU choices the preferences offer to the three the app reads. timing_unite_1000_circles (pathops) gets an ignore reason and checks that Unite gives one shape. Each changed assertion fails when the code under test is broken (an id renamed, a list emptied, a flush or instance dropped) and passes when it is restored. --- apps/vectorcraft/src/gpu/tests.rs | 7 +++---- crates/brush/src/tests.rs | 8 +++++++- crates/cad/src/hpgl/tests.rs | 2 +- crates/cad/src/tests.rs | 3 ++- crates/pathops/src/addons/pathtools/bridge.rs | 3 +++ crates/pathops/src/addons/pathtools/shapes.rs | 2 +- .../pathops/src/addons/pathtools/shared_edge/tests.rs | 6 ++---- crates/pathops/tests/it/ops.rs | 6 ++++-- crates/plugins/src/permissions.rs | 10 ++++------ crates/scriptcheck/src/tests.rs | 2 ++ crates/three-d/src/shadow/tests.rs | 2 +- crates/three-d/src/solid/tests.rs | 2 +- crates/three-d/src/solid/tests_face_map.rs | 3 ++- crates/three-d/src/tests.rs | 2 +- crates/three-d/src/tests/classic.rs | 6 ++---- crates/tools/src/distort/arap.rs | 3 ++- crates/tools/src/draw2/gesture/tests.rs | 3 ++- crates/tools/src/quickpen/tests.rs | 4 +--- 18 files changed, 41 insertions(+), 33 deletions(-) diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 4b660854f6..118a78006c 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() { let saved = prefs.to_json(); assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power); } - // Every choice Preferences offer means something here. - for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES { - assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}"); - } + // Preferences offer the three choices read above, and no other. + let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect(); + assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]); } #[test] diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 01821a08f1..7abfb33a4e 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2220,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() { serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) ); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect(); + assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids"); + assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel)); + assert_eq!(Variation::parse("wheel"), None); assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } @@ -2228,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() { #[test] fn junk_pressure_brushes_draw_finite_art() { let bp = preview_path(120.0, 24.0); + let mut drawn = 0; for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] { for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] { let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile)); @@ -2236,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() { all_points(n, &mut pts); } assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}"); + drawn += usize::from(!pts.is_empty()); } } + assert_eq!(drawn, 12, "brushes that draw"); } /// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says. diff --git a/crates/cad/src/hpgl/tests.rs b/crates/cad/src/hpgl/tests.rs index 9a350707a6..fdc31cb6cf 100644 --- a/crates/cad/src/hpgl/tests.rs +++ b/crates/cad/src/hpgl/tests.rs @@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() { let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;"); let widths: Vec<f64> = leaves(&i.document).iter().map(|n| stroke(n).width).collect(); let want = [MM, 2.0 * MM, MM, 0.35 * MM]; - assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); + assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); } #[test] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 6140395323..16f4f97082 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let o = DxfOptions { crop: true, ..opts(&d) }; - assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); + // The red fill: its outline and its hatch. + assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]); } /// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it. diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs index 2b2fd9512e..f1eaa29283 100644 --- a/crates/pathops/src/addons/pathtools/bridge.rs +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -816,11 +816,14 @@ mod tests { // Squaring these lengths overflows f64. let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153)); let sp = smooth_bridge(a, b, 5e153).unwrap(); + // At least one anchor for each of the two circles and the two arcs. + assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len()); assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); assert_smooth(&sp); // The two radius sums fit in f64, but not their total. let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307)); let sp = smooth_bridge(a, b, 1.5e308).unwrap(); + assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len()); assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); // The arcs' centers would lie beyond the largest f64. let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308)); diff --git a/crates/pathops/src/addons/pathtools/shapes.rs b/crates/pathops/src/addons/pathtools/shapes.rs index e0ecc241be..dc61429c34 100644 --- a/crates/pathops/src/addons/pathtools/shapes.rs +++ b/crates/pathops/src/addons/pathtools/shapes.rs @@ -609,12 +609,12 @@ mod tests { fn each_kind_draws_a_closed_outline_in_its_box() { for kind in ShapeKind::ALL { let s = shape(kind); - assert_eq!(ShapeKind::parse(kind.id()), Some(kind)); assert_eq!(s.check(), Ok(()), "{kind:?}"); let p = s.path().unwrap(); assert!(closed(&p) && within_box(&p, &s), "{kind:?}: {:?}", p.bounds()); assert!(p.anchors().all(|(_, _, a)| a.p.x.is_finite() && a.p.y.is_finite())); } + assert_eq!(ShapeKind::parse("gear"), Some(ShapeKind::Gear)); assert_eq!(ShapeKind::parse("cloud"), None); } diff --git a/crates/pathops/src/addons/pathtools/shared_edge/tests.rs b/crates/pathops/src/addons/pathtools/shared_edge/tests.rs index 38e7c49e3b..ef84d72f83 100644 --- a/crates/pathops/src/addons/pathtools/shared_edge/tests.rs +++ b/crates/pathops/src/addons/pathtools/shared_edge/tests.rs @@ -262,9 +262,7 @@ fn a_smooth_end_whose_handles_part_turns_into_a_corner() { } #[test] -fn follow_names_round_trip() { - for f in Follow::ALL { - assert_eq!(Follow::parse(f.id()), Some(f)); - } +fn follow_names_parse() { + assert_eq!(Follow::parse("b"), Some(Follow::Second)); assert_eq!(Follow::parse("up"), None); } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index e26d0e69e9..504d8af795 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -738,6 +738,8 @@ fn simplify_levels_and_auto_simplify() { #[test] fn smooth_rounds_corners() { let s = smooth(&rect(0.0, 0.0, 10.0, 10.0), 1.0); + // The four corners stay, each made smooth. + assert_eq!(s.anchor_count(), 4, "{s:?}"); assert!(s.anchors().all(|(_, _, a)| a.has_in() && a.has_out())); let same = smooth(&rect(0.0, 0.0, 10.0, 10.0), 0.0); assert_eq!(same, rect(0.0, 0.0, 10.0, 10.0)); @@ -959,7 +961,7 @@ fn grid_split() { } #[test] -#[ignore] +#[ignore = "benchmark: prints how long Unite takes on 1000 circles; run by hand with --ignored"] fn timing_unite_1000_circles() { let mut seed = 0x1234_5678_u64; let mut rnd = || { @@ -971,8 +973,8 @@ fn timing_unite_1000_circles() { let circles: Vec<Shape> = (0..1000).map(|i| shape(circle(rnd() * 1000.0, rnd() * 1000.0, 5.0 + rnd() * 30.0), i)).collect(); let t = std::time::Instant::now(); let r = pathfinder(PathfinderOp::Unite, &circles); + assert_eq!(r.len(), 1, "Unite gives one compound shape"); println!("unite 1000 circles: {} ms, {} anchors", t.elapsed().as_millis(), r[0].path.anchor_count()); - assert!(!r.is_empty()); } #[test] diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index a78aeec09b..f7cf875a6c 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -330,13 +330,11 @@ mod tests { use super::*; #[test] - fn names_round_trip_and_serialize_as_names() { - for p in ALL { - assert_eq!(Permission::parse(p.name()), Some(p)); - assert_eq!(serde_json::to_value(p).unwrap(), serde_json::json!(p.name())); - } + fn names_parse_and_serialize_as_names() { + assert_eq!(serde_json::to_value(ALL).unwrap(), serde_json::json!(names(&ALL)), "saved names are the names"); + assert_eq!(Permission::parse("doc.write"), Some(Permission::DocWrite)); assert_eq!(Permission::parse("document.read"), None); - assert!(RESERVED.iter().all(|r| Permission::parse(r).is_none()), "reserved names are not granted"); + assert!(!RESERVED.is_empty() && RESERVED.iter().all(|r| Permission::parse(r).is_none()), "reserved names are not granted"); } #[test] diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index ea745aaebf..1edd1480f6 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -2697,6 +2697,8 @@ fn a_file_two_branches_include_is_followed_from_the_shallower_one() { ]); let limits = Limits { include_depth: 3, ..Limits::default() }; let r = check("main.jsx", b"#include 'a.jsxinc'\n#include 'b.jsxinc'\n", Some(&mut m), &limits); + // One row per #include line: main's two, a's, b's, c's and shared's. + assert_eq!(r.includes.len(), 6, "{:?}", includes(&r)); assert!(r.includes.iter().all(|i| i.status == IncludeStatus::Checked), "{:?}", includes(&r)); assert_eq!(r.outside.iter().map(|o| o.id).collect::<Vec<_>>(), ["network"]); } diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs index f6f9806a43..790d5491c6 100644 --- a/crates/three-d/src/shadow/tests.rs +++ b/crates/three-d/src/shadow/tests.rs @@ -209,7 +209,7 @@ fn every_effect_casts_a_shadow() { assert!(plane.path(Shadow::default()).is_some()); let mut inflate = ShadowCaster::new(); let results = inflate.inflate(&[(&path, FillRule::NonZero)], &[true], bounds, Inflate::default(), View::default()); - assert!(results.iter().all(Result::is_ok)); + assert!(results.len() == 1 && results[0].is_ok(), "one result for the one path"); assert!(inflate.path(Shadow::default()).is_some()); let mut revolve = ShadowCaster::new(); revolve.revolve(&path, FillRule::NonZero, bounds, Revolve::default()).unwrap(); diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index a4db35adb0..570ea28d4d 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -880,7 +880,7 @@ fn inflate_cells_across_a_hole_edge_are_cut_to_the_shape() { let (p, r) = shape(&b); let v = View { rotation_x: -21.88, rotation_y: -23.4, rotation_z: 9.06, ..front() }; let f = inflate(&p, FillRule::EvenOdd, r, Inflate::default(), v).unwrap(); - assert!(f.iter().all(|f| f.contours.len() == 1), "every facet is one piece of the surface"); + assert!(!f.is_empty() && f.iter().all(|f| f.contours.len() == 1), "every facet is one piece of the surface"); // Straight on, the facets still cover exactly the shape. let flat = inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap(); assert!(close(area(&flat), 220.0 * 220.0 - 100.0 * 90.0, 1e-3), "{}", area(&flat)); diff --git a/crates/three-d/src/solid/tests_face_map.rs b/crates/three-d/src/solid/tests_face_map.rs index ebbe95448a..b0fb4d4717 100644 --- a/crates/three-d/src/solid/tests_face_map.rs +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -77,7 +77,8 @@ fn a_plane_has_only_a_front_and_a_hollow_solid_none() { let hollow = Extrude { cap: false, ..Extrude::default() }; assert_eq!(extrude_face_map(bounds, hollow, view, PlanarFace::Front), None); let facets = extrude(&path, FillRule::NonZero, bounds, hollow, view).unwrap(); - assert!(facets.iter().all(|f| f.end.is_none())); + // A hollow extrusion still draws its sides, and none of them is an end. + assert!(!facets.is_empty() && facets.iter().all(|f| f.end.is_none())); } #[test] diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index 069013c808..46cf515f08 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -181,7 +181,7 @@ fn perspective_runs_0_to_160_degrees_with_the_eye_outside_the_object() { assert!(eyes.windows(2).all(|w| w[0] > w[1]), "{eyes:?}"); let (p, b) = cylinder(); let wide = revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 160.0, ..Default::default() }).unwrap(); - assert!(wide.iter().flat_map(|f| &f.points).all(|q| q.x.is_finite() && q.y.is_finite())); + assert!(!wide.is_empty() && wide.iter().flat_map(|f| &f.points).all(|q| q.x.is_finite() && q.y.is_finite())); assert_eq!(wide, revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 400.0, ..Default::default() }).unwrap()); } #[test] diff --git a/crates/three-d/src/tests/classic.rs b/crates/three-d/src/tests/classic.rs index f460297453..fc0b703741 100644 --- a/crates/three-d/src/tests/classic.rs +++ b/crates/three-d/src/tests/classic.rs @@ -87,10 +87,8 @@ fn blend_steps_round_the_shading_to_that_many_levels() { } #[test] -fn surfaces_round_trip_through_their_ids() { - for surface in ClassicSurface::ALL { - assert_eq!(ClassicSurface::parse(surface.id()), Some(surface)); - } +fn surfaces_parse_from_their_ids() { + assert_eq!(ClassicSurface::parse("none"), Some(ClassicSurface::NoShading)); assert_eq!(ClassicSurface::parse("glossy"), None); assert_eq!(ClassicSurface::default(), ClassicSurface::Plastic); } diff --git a/crates/tools/src/distort/arap.rs b/crates/tools/src/distort/arap.rs index 10c355544c..4740bf556a 100644 --- a/crates/tools/src/distort/arap.rs +++ b/crates/tools/src/distort/arap.rs @@ -758,11 +758,12 @@ mod tests { }; // One pin, held at 0.4 rad: the whole shape turns rigidly around it. let d = deform(&m, &[Pin { angle: Some(0.4), ..Pin::new(c, c) }]); + assert!(!m.verts.is_empty() && d.len() == m.verts.len(), "{} of {}", d.len(), m.verts.len()); let err = m.verts.iter().zip(&d).map(|(a, b)| rot(*a).distance(*b)).fold(0.0, f64::max); assert!(err < 0.05, "{err}"); // A free pin alone leaves the shape where it is. let d = deform(&m, &[Pin::new(c, c)]); - assert!(m.verts.iter().zip(&d).all(|(a, b)| a.distance(*b) < 1e-3)); + assert!(d.len() == m.verts.len() && m.verts.iter().zip(&d).all(|(a, b)| a.distance(*b) < 1e-3)); // Held ends: the turned end turns, the other end stays. let left = Point::new(10.0, 50.0); let pins = [Pin { angle: Some(0.5), ..Pin::new(left, left) }, Pin::new(Point::new(190.0, 50.0), Point::new(190.0, 50.0))]; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index c8aa002add..41e378649c 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3752,7 +3752,8 @@ fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_durin press(&mut t, upright, 0.5, PointerKind::Drag, 150.0); near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); let released = t.stroke_json(); - assert!(released.as_array().is_some_and(|a| a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); + // One entry per press so far (the press and two drags), each of three numbers. + assert!(released.as_array().is_some_and(|a| a.len() == 3 && a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); press(&mut t, upright, 0.5, PointerKind::Up, 150.0); } diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 34311e9d96..f182ce3787 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -139,9 +139,7 @@ fn actions_cycle_and_name_themselves() { assert_eq!(Stroke::Line.next(), Stroke::ContinuousArc); assert_eq!(Stroke::ContinuousArc.next(), Stroke::SharpArc); assert_eq!(Stroke::SharpArc.next(), Stroke::Line); - for s in Stroke::ALL { - assert_eq!(Stroke::parse(s.name()), Some(s)); - } + assert_eq!(Stroke::parse("sharpArc"), Some(Stroke::SharpArc)); assert_eq!(Stroke::parse("arc"), None); } From 52d08f0f9caea8b9dd4271764306d3827c41add7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:38:19 -0800 Subject: [PATCH 66/71] Tests: SVG, PDF and EPS tests check what they claim Assertions that ran all() over a list that could be empty now check the list's length first: mesh points, image inks, glyph origins, imported text, the PDF mesh and arrowhead paths, and the resampled CMYK pixels. An image that takes a Warp from its art style is checked to keep none of the look's fills and strokes, instead of checking each of none. The convolve-matrix tests check that the filtered rectangle is imported, not only that the import returned Ok. The fan-out clip path test moves to a unit test that counts the clip paths read. The self-nesting symbol test checks that the other symbol comes back. The EPS level and preview id test checks the param values and the trimming and case rules instead of looping over every value. The ignored PDF text-heavy timing run says why it is ignored. A gradient that repeats or reflects with no stops now paints as one that pads. Before, PDF export wrote it as two 160 by 160 images and EPS wrote three runs of a conic where one that pads writes one; `Gradient::is_spread` is false without stops. `paint.setFill`'s params still report the spread. --- crates/color/src/gradient.rs | 5 +-- crates/color/src/gradient/spread/tests.rs | 4 +++ crates/eps/src/import/ai/mesh.rs | 2 ++ crates/eps/src/import/ai/read/ops.rs | 3 +- crates/eps/src/import/ai/tests.rs | 1 + crates/eps/src/import/tests_images.rs | 1 + crates/eps/src/import/tests_native.rs | 1 + crates/eps/src/tests.rs | 35 +++++++++++++-------- crates/pdf/src/images.rs | 1 + crates/pdf/src/tests/mesh_export.rs | 5 ++- crates/pdf/src/tests/spread.rs | 20 +++++++----- crates/pdf/src/tests/stroke.rs | 1 + crates/pdf/src/tests/text_placement.rs | 2 +- crates/svg/src/import/convert.rs | 37 +++++++++++++++++++++++ crates/svg/tests/convolve_overflow.rs | 23 +++++++++----- crates/svg/tests/it/import_details.rs | 15 --------- crates/svg/tests/it/import_text.rs | 6 +++- crates/svg/tests/it/svg_glyphs.rs | 1 + crates/svg/tests/it/symbols_layers.rs | 5 ++- crates/tools/src/params.rs | 2 +- 20 files changed, 120 insertions(+), 50 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 5982e37552..0f520b2f9d 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -464,9 +464,10 @@ impl Gradient { self.repeats.clamp(1, MAX_REPEATS) } /// Does it paint something other than its end colors past the ends of its stops, or run its - /// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects? + /// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or + /// reflects? One without stops paints as one that pads. pub fn is_spread(&self) -> bool { - !self.spread.is_pad() && self.kind != GradientKind::Freeform + !self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty() } /// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever /// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal diff --git a/crates/color/src/gradient/spread/tests.rs b/crates/color/src/gradient/spread/tests.rs index ab088293da..c42b1acd61 100644 --- a/crates/color/src/gradient/spread/tests.rs +++ b/crates/color/src/gradient/spread/tests.rs @@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() { let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3); assert_eq!(free.spread_param(0.7), 0.7); assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread()); + // Without stops it paints as one that pads. + let empty = Gradient { stops: vec![], ..repeat.clone() }; + assert!(!empty.is_spread()); + assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1)); assert!(repeat.spread_param(f64::NAN).is_nan()); // A count out of range (set in code) counts as the nearest one in range. assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1); diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 9e8a77e5dc..8e2a46c852 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -873,6 +873,7 @@ mod tests { } r.entry(&[V::Num(0.0), name("E")], Affine::IDENTITY); let mesh = r.one_mesh().unwrap(); + assert_eq!(mesh.points.len(), 9, "{mesh:?}"); assert!(mesh.points.iter().all(|q| q.p.x.is_finite() && q.p.y.is_finite() && q.handles.iter().all(|h| h.x.is_finite() && h.y.is_finite()))); } @@ -962,6 +963,7 @@ mod tests { assert!(!reader.unread, "{with_opacity} {data_first}"); let mesh = reader.one_mesh().unwrap(); let want = if with_opacity { 0.25 } else { 1.0 }; + assert_eq!(mesh.points.len(), 4, "{with_opacity} {data_first}: {mesh:?}"); assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}"); } } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index bb5343e4f4..0b6ac8b9dd 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -2217,7 +2217,8 @@ mod tests { let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp"); let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect(); assert_eq!(ids, ["warp.arc"]); - assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}"); + // The image's own look: none of the look's fills and strokes. + assert!(ap.items.is_empty(), "{ap:?}"); // Not on a path, nor on an image with an opacity mask. assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none()); let mut masked = image.clone(); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 0d09cf8dab..9ef4cbc840 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -291,6 +291,7 @@ fn object_tags_without_an_object_before_them_tag_nothing() { let doc = read7(&layer7("L", &body)).doc; let mut all = art(&doc); all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::<Vec<_>>()); + assert!(!all.is_empty(), "{body}: no art"); assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}"); } for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] { diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 6830fb5b41..e7fd734240 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -241,6 +241,7 @@ fn cmyk_jpegs_keep_their_ink_amounts() { /ImageMatrix [2 0 0 -2 0 2] /DataSource currentfile /ASCIIHexDecode filter /DCTDecode filter >> image\n{data}>" )); let got = inks(&r).data; + assert_eq!(got.len(), want.len(), "{decode}: {got:?}"); assert!(got.iter().zip(&want).all(|(a, b)| a.abs_diff(*b) <= 3), "{decode}: {got:?}"); } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index c5b6b61d58..9fdeba9ff5 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8238,6 +8238,7 @@ fn type_with_a_distort_effect_comes_in_as_type_with_it_live() { // An angle that isn't a number: the drawing as paths, and no effect on the type. let (texts, paths) = open("Adobe Twirl", "NaN /Real (angle) ,\n"); assert_eq!(paths, 1, "{texts:?}"); + assert_eq!(texts.len(), 1, "{texts:?}"); assert!(texts.iter().all(|(_, effects)| effects.is_empty()), "{texts:?}"); } diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 3b45578deb..dc40025954 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -301,12 +301,23 @@ fn spread_gradients_are_written_with_their_stops_repeated() { fn a_spread_gradient_without_stops_is_written() { use vectorcraft_color::GradientSpread; for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { - let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); - let paint = Paint::Gradient(Box::new(g)); - let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]); - export(&d, &opts(&d), None, None).unwrap(); - export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap(); - crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap(); + let doc = |spread: GradientSpread| { + let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]) + }; + let (d, pad) = (doc(GradientSpread::Repeat), doc(GradientSpread::Pad)); + assert_eq!(page_of(&d, &opts(&d)), page_of(&pad, &opts(&pad)), "{kind:?}: EPS"); + assert_eq!( + export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap().bytes, + export_legacy_ai(&pad, &LegacyAiOptions::default()).unwrap().bytes, + "{kind:?}: legacy .ai" + ); + assert_eq!( + crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap().program, + crate::export_ai_editing(&pad, &crate::AiEditingOptions::default()).unwrap().program, + "{kind:?}: .ai editing data" + ); } } @@ -2359,15 +2370,15 @@ fn symbol_art_effects_are_written_where_they_draw() { #[test] fn level_preview_and_overprint_ids_read_back() { - for l in Level::ALL { - assert_eq!(Level::from_id(l.id()), Some(l)); - } + assert_eq!(Level::from_id("3"), Some(Level::Three)); assert_eq!(Level::from_id("LanguageLevel 2"), Some(Level::Two)); assert_eq!(Level::from_id("1"), None); - for p in Preview::ALL { - assert_eq!(Preview::from_id(p.id()), Some(p)); - } + assert_eq!(Level::from_id("23"), None); + assert_eq!(Preview::from_id(" TIFFCOLOR "), Some(Preview::TiffColor)); + assert_eq!(Preview::from_id("tiffBw"), Some(Preview::TiffBlackWhite)); + assert_eq!(Preview::from_id("tiff"), None); assert_eq!(Overprint::from_id("DISCARD"), Some(Overprint::Discard)); + assert_eq!(Overprint::from_id(""), None); } #[test] diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index bdf51da6f8..d6d68ee02b 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -915,6 +915,7 @@ mod tests { let (inks, alpha) = resampled_inks(inks, Some(alpha.clone()), &rule(&c, Kind::Color), (4, 1)).unwrap(); let alpha = alpha.unwrap(); let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; + assert_eq!((inks.as_chunks::<4>().0.len(), alpha.len()), (4, 4), "{method}"); for (p, &a) in inks.as_chunks::<4>().0.iter().zip(&alpha) { assert!(a > 0 && p.iter().zip([40, 80, 120, 160]).all(|(&c, want)| m(c, a).abs_diff(m(want, a)) <= 1), "{method}: {p:?} at {a}"); } diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index cf8ad25e3b..b2e8ecb2f6 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -73,11 +73,14 @@ fn a_cmyk_mesh_is_written_smooth_in_its_inks() { let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); let (meshes, paths) = kinds(&back); assert!(meshes >= 1 && paths <= 4, "meshes {meshes}, paths {paths}"); + let mut points = vec![]; back.walk(|n| { if let NodeKind::Mesh(m) = &n.kind { - assert!(m.points.iter().all(|p| matches!(p.color, Color::Cmyk { .. })), "{:?}", m.points); + points.extend(m.points.iter().map(|p| p.color)); } }); + assert!(!points.is_empty(), "the meshes have points"); + assert!(points.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{points:?}"); assert_similar(&render_artboard(&d), &render_artboard(&back), 6.0, 0.02); } diff --git a/crates/pdf/src/tests/spread.rs b/crates/pdf/src/tests/spread.rs index ebfe655f9a..0a852ba664 100644 --- a/crates/pdf/src/tests/spread.rs +++ b/crates/pdf/src/tests/spread.rs @@ -236,17 +236,21 @@ fn a_perceptual_spot_gradient_too_long_once_repeated_is_an_image() { } } -/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked. +/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked, as the +/// same gradient that pads does. #[test] fn a_spread_gradient_without_stops_exports() { for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { - let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); - let paint = Paint::Gradient(Box::new(g)); - let mut d = Document::new(200.0, 200.0); - let (l, id) = (d.layers[0].id, d.alloc_id()); - let ap = Appearance::basic(paint.clone(), paint, 4.0); - d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap(); - export(&d, &PdfOptions::default()).unwrap(); + let written = |spread: GradientSpread| { + let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + let mut d = Document::new(200.0, 200.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let ap = Appearance::basic(paint.clone(), paint, 4.0); + d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap(); + uncompressed(&d, &PdfOptions { created: Some(0), ..PdfOptions::uncompressed() }) + }; + assert_eq!(written(GradientSpread::Repeat), written(GradientSpread::Pad), "{kind:?}"); } } diff --git a/crates/pdf/src/tests/stroke.rs b/crates/pdf/src/tests/stroke.rs index d57cbc42d0..881ebd4a4c 100644 --- a/crates/pdf/src/tests/stroke.rs +++ b/crates/pdf/src/tests/stroke.rs @@ -90,5 +90,6 @@ fn line_and_head_share_one_opacity_group() { _ => {} }); assert!(group_opacity.is_some_and(|o| (o - 0.5).abs() < 0.01), "{group_opacity:?}"); + assert!(!leaf_opacities.is_empty(), "the line and its head come back as paths"); assert!(leaf_opacities.iter().all(|o| (o - 1.0).abs() < 1e-3), "{leaf_opacities:?}"); } diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index 31ea411840..f64f8c4173 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -745,7 +745,7 @@ fn text_heavy(columns: usize, rows: usize) -> Vec<u8> { /// How long a text-heavy file takes to open as type (run by hand: `-- --ignored --nocapture`). #[test] -#[ignore] +#[ignore = "timing, run by hand"] fn perf_text_heavy_open() { let bytes = text_heavy(20, 200); for _ in 0..2 { diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 676708a09d..a5e7bc3e63 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -297,3 +297,40 @@ pub(super) fn rule(r: usvg::FillRule) -> FillRule { usvg::FillRule::EvenOdd => FillRule::EvenOdd, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Clip paths are shared, so children that each name the next one multiply at every level: ten + /// children on seven levels would take 10^7 reads unbounded. The paths read stay within ten (the + /// children of one clip path) per clip path read, and the clip still has shapes. + #[test] + fn clip_paths_whose_children_fan_out_are_read_a_bounded_number_of_times() { + let mut defs = String::from(r#"<clipPath id="c0"><rect width="10" height="10"/></clipPath>"#); + for n in 1..8 { + let kids = format!(r#"<rect width="10" height="10" clip-path="url(#c{})"/>"#, n - 1).repeat(10); + defs += &format!(r#"<clipPath id="c{n}">{kids}</clipPath>"#); + } + let svg = format!( + r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><defs>{defs}</defs><rect width="20" height="20" clip-path="url(#c7)"/></svg>"# + ); + let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap(); + let cp = tree + .root() + .children() + .iter() + .find_map(|c| match c { + usvg::Node::Group(g) => g.clip_path(), + _ => None, + }) + .unwrap(); + let visits = std::cell::Cell::new(0usize); + let shapes = clip_shapes(cp, Affine::IDENTITY, &|_, _| { + visits.set(visits.get() + 1); + None + }); + assert!(!shapes.is_empty()); + assert!(visits.get() <= 10 * MAX_CLIP_READS, "{} paths read", visits.get()); + } +} diff --git a/crates/svg/tests/convolve_overflow.rs b/crates/svg/tests/convolve_overflow.rs index 4c080e1944..2971027a67 100644 --- a/crates/svg/tests/convolve_overflow.rs +++ b/crates/svg/tests/convolve_overflow.rs @@ -8,8 +8,17 @@ // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use vectorcraft_doc::NodeKind; use vectorcraft_svg::import; +/// How many paths `svg` imports as: each file here holds one filtered rectangle. +fn paths(svg: &str) -> usize { + let d = import(svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut n = 0; + d.walk(|node| n += usize::from(matches!(node.kind, NodeKind::Path { .. }))); + n +} + /// An overflowing `order` with a `kernelMatrix` that parses (usvg `parser/filter.rs`). #[test] fn convolve_matrix_overflowing_order_with_kernel_is_refused() { @@ -44,7 +53,7 @@ fn convolve_matrix_large_but_fitting_order_still_imports() { let svg = format!( r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="{order}"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"# ); - assert!(import(&svg).is_ok(), "order={order} fits the u32 multiply and must keep importing"); + assert_eq!(paths(&svg), 1, "order={order} fits the u32 multiply and must keep importing"); } } @@ -56,7 +65,7 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { let svg = format!( r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="{order}" {kernel}/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"# ); - assert!(import(&svg).is_ok(), "order={order} is usvg's pass-through and must keep importing"); + assert_eq!(paths(&svg), 1, "order={order} is usvg's pass-through and must keep importing"); } } @@ -65,18 +74,18 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { #[test] fn convolve_matrix_unparseable_or_mismatched_kernel_still_imports() { let mismatched = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="0 0 0 0 1 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; - assert!(import(mismatched).is_ok(), "a kernel of the wrong length is usvg's pass-through"); + assert_eq!(paths(mismatched), 1, "a kernel of the wrong length is usvg's pass-through"); let unparseable = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="1e999 0 0 0 0 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; - assert!(import(unparseable).is_ok(), "an unparseable kernel is usvg's pass-through"); + assert_eq!(paths(unparseable), 1, "an unparseable kernel is usvg's pass-through"); } /// Sane kernels keep importing: 3×3, 2×2, and a defaulted order. #[test] fn sane_convolve_matrices_still_import() { let three = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="3" kernelMatrix="0 0 0 0 1 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; - assert!(import(three).is_ok(), "an ordinary filter must still import"); + assert_eq!(paths(three), 1, "an ordinary filter must still import"); let two = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix order="2" kernelMatrix="0 1 1 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; - assert!(import(two).is_ok(), "a small kernel must still import"); + assert_eq!(paths(two), 1, "a small kernel must still import"); let defaulted = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><filter id="f"><feConvolveMatrix kernelMatrix="0 0 0 0 1 0 0 0 0"/></filter><rect width="4" height="4" filter="url(#f)"/></svg>"#; - assert!(import(defaulted).is_ok(), "a filter without order must still import"); + assert_eq!(paths(defaulted), 1, "a filter without order must still import"); } diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index a4046e3fe7..c96dd72adb 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -552,21 +552,6 @@ fn clip_path_child_with_chained_clip_path_intersects() { assert_eq!(mine.over_white(100, 25), [255, 255, 255], "top right is cut by inner clip"); } -/// Clip paths are shared, so children that each name the next one multiply at every level: ten -/// children on seven levels would take 10^7 reads unbounded. The import must still finish. -#[test] -fn clip_paths_whose_children_fan_out_still_import() { - let mut defs = String::from(r#"<clipPath id="c0"><rect width="10" height="10"/></clipPath>"#); - for n in 1..8 { - let kids = format!(r#"<rect width="10" height="10" clip-path="url(#c{})"/>"#, n - 1).repeat(10); - defs += &format!(r#"<clipPath id="c{n}">{kids}</clipPath>"#); - } - let svg = format!( - r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><defs>{defs}</defs><rect width="20" height="20" clip-path="url(#c7)"/></svg>"# - ); - assert!(import_with_report(&svg).is_ok()); -} - #[test] fn clip_path_deep_chain_preserves_art() { let mut defs = String::from(r#"<clipPath id="c0"><rect width="100" height="100"/></clipPath>"#); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index c8a1cfd4ed..9c1cac5890 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -226,7 +226,10 @@ fn a_use_of_a_text_passes_its_properties_on_to_the_text() { #[test] fn a_use_inside_the_text_it_shows_opens() { let d = open(r##"<text id="t" y="50" font-size="20">HI<use href="#t" font-size="100"/><tspan><use href="#t"/></tspan></text>"##); - assert!(texts(&d).iter().all(|t| close(t.first_style().size, 20.0, 1e-9)), "{:?}", texts(&d)); + let t = texts(&d); + assert_eq!(t.len(), 1, "{t:?}"); + assert_eq!(t[0].plain_text(), "HI"); + assert!(close(t[0].first_style().size, 20.0, 1e-9), "{t:?}"); } /// Past 1 MiB of text built for `<use>` elements, the rest show their text with its own properties. @@ -1232,6 +1235,7 @@ fn vertical_writing_mode_runs_down_a_path() { let b = path.bounds().unwrap(); assert!(close(b.x0, b.x1, 1e-9) && close(b.y0, 20.0, 1e-9) && b.height() > 20.0, "{b:?}"); let o = glyph_origins(t); + assert_eq!(o.len(), 4, "{o:?}"); assert!(o.windows(2).all(|w| w[1].y > w[0].y), "glyphs step down: {o:?}"); // The em box is centred on the column. let lay = layout(FontDb::global(), t); diff --git a/crates/svg/tests/it/svg_glyphs.rs b/crates/svg/tests/it/svg_glyphs.rs index 3e4ba8b697..b48c486446 100644 --- a/crates/svg/tests/it/svg_glyphs.rs +++ b/crates/svg/tests/it/svg_glyphs.rs @@ -56,6 +56,7 @@ fn current_color_and_context_colours_are_the_texts() { let (art, _) = glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap(); let mut strokes = vec![]; art.walk(&mut |c| strokes.push(c.appearance.stroke_paint())); + assert_eq!(strokes.len(), seen.len(), "the same art without the text's stroke: {strokes:?}"); assert!(strokes.iter().all(|p| *p == Paint::None), "no stroke without the text's: {strokes:?}"); let plain = r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="glyph1"><path fill="#f00" d="M0 0h5v-5z"/></g></svg>"##; assert!(!glyph_art(plain.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1, "a document in its own colours"); diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 1d1b4cc712..05e70265fa 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -554,7 +554,10 @@ fn symbols_inside_themselves_end() { d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(g) }); instance(&mut d, "Loop", Affine::translate((20.0, 20.0))); let svg = export(&d, &ExportOptions::default()); - assert!(import(&svg).is_ok(), "{svg}"); + // The symbol that holds itself is not written into itself; the other one still comes back. + assert!(svg.matches("<use ").count() <= 3, "{svg}"); + let back = import(&svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + assert!(back.symbols.iter().any(|s| s.name == "My Mark"), "{svg}"); } /// Two layers, the second hidden, each with a square. diff --git a/crates/tools/src/params.rs b/crates/tools/src/params.rs index c7a205a19e..9fe1fb2138 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -79,7 +79,7 @@ pub fn gradient_params(g: &GradientPaint) -> Value { v["method"] = json!(g.gradient.method.id()); } // A freeform gradient has no ends to spread past (`paint.setFill` refuses a spread for one). - if g.gradient.is_spread() { + if !g.gradient.spread.is_pad() && g.gradient.kind != vectorcraft_color::GradientKind::Freeform { v["spread"] = json!(g.gradient.spread.label().to_lowercase()); } // A gradient that pads keeps its count for later. From 293bde7afeb94021fc484c3b69d8801e3651ff51 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:41:04 -0800 Subject: [PATCH 67/71] Tests: panel tests check results, not that a list is non-empty or every catalog has a row Panel tests that could pass on an empty list, that only checked a control was there, or that looped over every language or preset now check the result: - Character, Glyphs and OpenType: the underline, kashida, size, Up/Down, glyph form and Proportional Metrics checks compare the text each setting reaches (for example "AB" underlined, then none) instead of `all()` over the runs, which passed when a frame had no runs. - Actions: the built-in actions play on a selection and each makes an undo step, instead of only looking up their command ids. - Color Wheel: Show Out-of-Gamut Colors is checked by what the wheel and the box draw with it on and off. The test that loaded a profile and only checked the box was shown is removed, and two copies of the junk-parameter test are removed (the one in tests_color_wheel_vision.rs runs with and without a document). The error-translation tests check German and Japanese instead of every catalog. - History and Paragraph: the name and Mojikumi checks use a few languages instead of every catalog, and the Numbered List presets are checked by one style instead of every number style. - Graphic Styles, Stroke and Swatches: the rename, profile preview and row menu checks count what they read before checking each item. - Image Trace: the off-thread trace test waits on the trace's own channel through a new test-only `trace_runs::finish_all`, instead of polling with a sleep for up to 30 seconds. --- .../ui-egui/src/panels/actions/tests_files.rs | 22 +++++++-- crates/ui-egui/src/panels/character/tests.rs | 48 ++++++++++++------- crates/ui-egui/src/panels/glyphs/tests.rs | 17 ++++--- crates/ui-egui/src/panels/graphic_styles.rs | 3 +- crates/ui-egui/src/panels/history.rs | 19 ++++++-- .../ui-egui/src/panels/image_trace/tests.rs | 6 +-- crates/ui-egui/src/panels/opentype.rs | 21 +++++--- crates/ui-egui/src/panels/paragraph/tests.rs | 10 ++-- crates/ui-egui/src/panels/stroke.rs | 10 ++-- .../src/panels/swatches/tests/context_menu.rs | 4 +- .../src/panels/tests_color_wheel_box.rs | 22 ++------- .../src/panels/tests_color_wheel_gamut.rs | 48 +++++-------------- .../src/panels/tests_color_wheel_harmony.rs | 7 +-- .../src/panels/tests_color_wheel_opacity.rs | 11 ----- crates/ui-egui/src/trace_runs.rs | 27 ++++++++--- 15 files changed, 145 insertions(+), 130 deletions(-) diff --git a/crates/ui-egui/src/panels/actions/tests_files.rs b/crates/ui-egui/src/panels/actions/tests_files.rs index a88cbc36fe..396c3d6af9 100644 --- a/crates/ui-egui/src/panels/actions/tests_files.rs +++ b/crates/ui-egui/src/panels/actions/tests_files.rs @@ -53,12 +53,24 @@ fn browser_picks_load_and_replace_action_sets_without_a_file_reader() { } } +/// Each built-in action plays on a selection it applies to (text for Outline Text, two +/// overlapping rectangles otherwise) and edits the drawing, so its commands and their +/// parameters are ones the engine accepts. #[test] -fn defaults_are_valid_commands() { - for a in default_sets().actions { - for step in a.steps { - assert!(vectorcraft_engine::find_command(&step.command).is_some(), "{}", step.command); - } +fn built_in_actions_play_and_edit_the_drawing() { + for (idx, a) in default_sets().actions.iter().enumerate() { + let mut app = new_app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let ids: Vec<Value> = if a.steps.iter().any(|s| s.command.starts_with("type.")) { + vec![app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab"})).unwrap()["id"].clone()] + } else { + [10, 30].iter().map(|x| app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone()).collect() + }; + app.run("select.set", json!({ "ids": ids })).unwrap(); + app.ui.actions = default_list(); + let before = undo_steps(&app); + play(&mut app, 0, idx).unwrap_or_else(|e| panic!("{}: {e}", a.name)); + assert!(undo_steps(&app) > before, "{} edits the drawing", a.name); } } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 6713eb3033..d1f6be332e 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -7,6 +7,18 @@ use vectorcraft_doc::text::TypeAntiAlias; use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; use vectorcraft_engine::Session; +/// The different values in `items`, in the order they first appear: `[v]` when every item is `v`, +/// and empty when there are no items. +fn distinct<T: PartialEq>(items: impl IntoIterator<Item = T>) -> Vec<T> { + let mut out = Vec::new(); + for item in items { + if !out.contains(&item) { + out.push(item); + } + } + out +} + /// `value` is `want` (the panel's fields are single precision). fn near(value: Option<f32>, want: f64) -> bool { value.is_some_and(|v| (f64::from(v) - want).abs() < 1e-6) @@ -844,14 +856,16 @@ fn underline_command_underlines_a_mixed_selection() { let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap(); app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "underline": true})).unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); + // The underlined characters, in order. let underlined = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { - NodeKind::Text(t) => t.runs.iter().map(|r| r.style.underline).collect::<Vec<_>>(), + NodeKind::Text(t) => t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect::<String>(), _ => panic!("text"), }; + assert_eq!(underlined(&app), "A"); assert_eq!(super::toggle_underline(&mut app), Ok(json!(true))); - assert!(underlined(&app).iter().all(|u| *u), "{:?}", underlined(&app)); + assert_eq!(underlined(&app), "AB"); assert_eq!(super::toggle_underline(&mut app), Ok(json!(false))); - assert!(underlined(&app).iter().all(|u| !*u), "{:?}", underlined(&app)); + assert_eq!(underlined(&app), ""); } /// At a caret in text the Type tool edits, with no characters selected, the Character @@ -902,15 +916,15 @@ fn kashidas_menu_item_handles_default_and_mixed_ranges() { assert!(!state(&app, &row).1); fire(&mut app, &row); assert!(state(&app, &row).1); - let kashidas = |app: &VectorcraftApp| story_frame(app, id).runs.iter().map(|r| r.style.kashidas).collect::<Vec<_>>(); - assert!(kashidas(&app).iter().all(|v| *v)); + let kashidas = |app: &VectorcraftApp| distinct(story_frame(app, id).runs.iter().map(|r| r.style.kashidas)); + assert_eq!(kashidas(&app), [true]); app.select_tool("type"); app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); app.session.set_tool_option("select", &json!({"start": 1, "end": 1})); assert!(!state(&app, &row).0, "disabled at an empty caret"); // The result is not the point: a disabled row must leave the text as it was. let _ = run(&mut app, &row.id, &row.params); - assert!(kashidas(&app).iter().all(|v| *v), "an empty caret leaves all characters unchanged"); + assert_eq!(kashidas(&app), [true], "an empty caret leaves all characters unchanged"); } /// Reset Panel sets every character attribute the panel shows, except the font family, style @@ -1112,7 +1126,7 @@ fn select_all_in_threaded_text_formats_and_copies_the_whole_story() { crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap(); for id in [a, b] { let t = frame(&app, id); - assert!(t.runs.iter().all(|r| (r.style.size - 9.0).abs() < 1e-9), "every character of frame {id} is 9 pt"); + assert_eq!(distinct(t.runs.iter().map(|r| r.style.size)), [9.0], "every character of frame {id} is 9 pt"); assert!((t.para_at(0).space_before - 4.0).abs() < 1e-9, "frame {id}'s paragraphs take the space"); } assert!(intercept_text_command(&mut app, "edit.copy").is_some()); @@ -1174,9 +1188,9 @@ fn story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_lea assert_eq!(text_story(&app), Some(vec![NodeId(b), NodeId(c)])); format(&mut app, json!({"size": 9})); - assert!(story_sizes(&app, a).iter().all(|s| (*s - 12.0).abs() < 1e-9), "the frame that left keeps its size"); + assert_eq!(distinct(story_sizes(&app, a)), [12.0], "the frame that left keeps its size"); for id in [b, c] { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size"); + assert_eq!(distinct(story_sizes(&app, id)), [9.0], "frame {id} takes the size"); } } @@ -1262,26 +1276,28 @@ fn selection_tool_changes_reach_every_frame_of_the_story() { style(&mut app, json!({"size": 9})); assert_eq!(undo_steps(&app), steps + 1, "one undo step"); for id in frames { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size"); + assert_eq!(distinct(story_sizes(&app, id)), [9.0], "frame {id} takes the size"); } - assert!(story_sizes(&app, other).iter().all(|s| (*s - 12.0).abs() < 1e-9), "other type keeps its size"); + assert_eq!(distinct(story_sizes(&app, other)), [12.0], "other type keeps its size"); app.run("edit.undo", json!({})).unwrap(); for id in frames { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 12.0).abs() < 1e-9), "undo gives frame {id} its size back"); + assert_eq!(distinct(story_sizes(&app, id)), [12.0], "undo gives frame {id} its size back"); } format(&mut app, json!({"underline": true})); + let underline = |app: &VectorcraftApp, id: u64| distinct(story_frame(app, id).runs.iter().map(|r| r.style.underline)); for id in frames { - assert!(story_frame(&app, id).runs.iter().all(|r| r.style.underline), "frame {id} is underlined"); + assert_eq!(underline(&app, id), [true], "frame {id} is underlined"); } - assert!(story_frame(&app, other).runs.iter().all(|r| !r.style.underline)); + assert_eq!(underline(&app, other), [false]); // Tate-chu-yoko Settings and Warichu Settings set their values through `run_format`. run_format(&mut app, json!({"tcyUpDown": 2})).unwrap(); + let up_down = |app: &VectorcraftApp, id: u64| distinct(story_frame(app, id).runs.iter().map(|r| r.style.tcy_up_down)); for id in frames { - assert!(story_frame(&app, id).runs.iter().all(|r| (r.style.tcy_up_down - 2.0).abs() < 1e-9), "frame {id} takes Up/Down"); + assert_eq!(up_down(&app, id), [2.0], "frame {id} takes Up/Down"); } - assert!(story_frame(&app, other).runs.iter().all(|r| r.style.tcy_up_down.abs() < 1e-9)); + assert_eq!(up_down(&app, other), [0.0]); } /// The fields show a value only when every frame of the selected story has it: a hidden frame that diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index 0886975276..e8eae923bd 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -208,9 +208,7 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { assert!(!rows(&app).contains(&form_ref(GlyphForm::Jis78)), "hidden without Show East Asian Options"); app.session.prefs.show_east_asian_options = true; let shown = rows(&app); - for form in GlyphForm::ALL { - assert!(shown.contains(&form_ref(form)), "{form:?} in {shown:?}"); - } + assert!(shown.contains(&form_ref(GlyphForm::Jis78)), "shown with Show East Asian Options: {shown:?}"); const FAMILY: &str = "BIZ UDMincho"; if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); @@ -231,7 +229,7 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap(); select(&mut app, 0, 6); choose(&mut app, GlyphForm::Jis83); - assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Jis83), "亜唖", "{:?}", forms(&app)); app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap(); app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap(); select(&mut app, 3, 6); @@ -244,7 +242,12 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { assert_eq!(undo_len(&app), n); assert_eq!(forms(&app)[1].1, GlyphForm::Jis78); choose(&mut app, GlyphForm::Default); - assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Default), "亜唖", "{:?}", forms(&app)); +} + +/// The characters of `runs` (text and form) drawn in `form`, in order. +fn in_form(runs: &[(String, GlyphForm)], form: GlyphForm) -> String { + runs.iter().filter(|(_, f)| *f == form).map(|(text, _)| text.as_str()).collect() } /// At a caret the glyph form rows act on all the text of the object, so they are checked, and skipped as changing nothing, by @@ -256,14 +259,14 @@ fn glyph_form_items_at_a_caret_follow_all_the_text() { app.session.prefs.show_east_asian_options = true; let node = NodeId(id.as_u64().unwrap_or(0)); let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(node).unwrap().kind { - NodeKind::Text(t) => t.runs.iter().map(|r| r.style.glyph_form).collect::<Vec<_>>(), + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::<Vec<_>>(), _ => panic!("text"), }; app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "glyphForm": "jis78"})).unwrap(); select(&mut app, 6, 6); assert_eq!(selection_glyph_form(&app), None, "the caret's form is not every character's"); choose(&mut app, GlyphForm::Default); - assert!(forms(&app).iter().all(|f| *f == GlyphForm::Default), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Default), "亜唖", "{:?}", forms(&app)); app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "jis78"})).unwrap(); select(&mut app, 6, 6); assert_eq!(selection_glyph_form(&app), Some(GlyphForm::Jis78)); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index e6668323a8..7d59220a48 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1756,7 +1756,8 @@ mod tests { let app = panel.app(); let names: Vec<Vec<String>> = app.session.documents().iter().map(|st| st.doc.graphic_styles.iter().map(|g| g.name.clone()).collect()).collect(); - assert!(names.iter().all(|n| n.iter().any(|g| g == "Mine")), "no style is renamed: {names:?}"); + let kept = names.iter().filter(|n| n.iter().any(|g| g == "Mine")).count(); + assert_eq!(kept, 2, "both documents keep their style named Mine: {names:?}"); } /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 7650b4d79c..2e0c5b2c57 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -292,6 +292,15 @@ mod tests { use crate::tests::panel_harness::Panel; use craft::ui::contract::Role; + /// English and two translated interface languages, one of them with another script. + fn some_languages() -> [crate::i18n::Lang; 3] { + [ + crate::i18n::Lang::EN, + crate::i18n::Lang::from_code("de").expect("de registered"), + crate::i18n::Lang::from_code("ja").expect("ja registered"), + ] + } + /// A step named after a style lists the template's translation with the style's name in it as /// the document holds it, also when the name looks like a template, like a step with a row of /// its own (`Apply Brush`) or like another template's name; the Normal style's name is @@ -338,7 +347,7 @@ mod tests { /// plain row, else the menu item's row without the ellipsis; a name with no row has none. #[test] fn plain_steps_read_the_menu_row_and_unknown_steps_have_no_name() { - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { let menu_row = crate::i18n::has(lang, "Clean Up…").then(|| crate::i18n::tr(lang, "Clean Up…").trim_end_matches('…').to_string()); let plain_row = crate::i18n::has(lang, "Clean Up").then(|| crate::i18n::tr(lang, "Clean Up").to_string()); assert_eq!(step_name(lang, "Clean Up"), plain_row.or(menu_row), "{}", lang.code()); @@ -347,7 +356,7 @@ mod tests { assert_eq!(step_name(ja, "No Such Step"), None); } - /// Every built-in effect has one name in each language: History (and Edit › Undo and Redo) + /// Every built-in effect has one name in each language checked: History (and Edit › Undo and Redo) /// names the step that applied it, and the Appearance panel its row, with the text of its /// Effect menu item without the ellipsis, which is the effect's `@id` row or the row of its /// menu label with the ellipsis. @@ -366,7 +375,7 @@ mod tests { } assert!(steps.len() * 2 > vectorcraft_effects::effect_catalog().len(), "only {} effects applied", steps.len()); let mut differ = Vec::new(); - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { crate::i18n::set_current(lang); for (e, h) in &steps { let cmd = if e.defaults.as_object().is_some_and(|o| o.is_empty()) { "effect.apply" } else { "effect.dialog" }; @@ -385,14 +394,14 @@ mod tests { } /// A step another command names like an effect (Object › Transform's `Transform`, the name of - /// Distort & Transform › Transform) keeps its own name in every language. + /// Distort & Transform › Transform) keeps its own name in each language checked. #[test] fn a_step_named_like_an_effect_keeps_its_own_name() { let mut app = app_with_two_rectangles(); app.session.execute("object.transform", &json!({ "matrix": [1, 0, 0, 1, 5, 0] })).unwrap(); let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); assert_eq!((h.label.as_str(), h.effect()), ("Transform", None)); - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { assert_eq!(entry_name(lang, &h), step_name(lang, "Transform"), "{}", lang.code()); } } diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 1c7a51edc3..7a1085a152 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1280,11 +1280,7 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { assert_eq!(undo(&panel.app()), steps, "not traced yet"); { let mut app = panel.app(); - let t0 = std::time::Instant::now(); - while !app.trace_runs.running.is_empty() && t0.elapsed() < std::time::Duration::from_secs(30) { - crate::trace_runs::poll(&mut app); - std::thread::sleep(std::time::Duration::from_millis(5)); - } + crate::trace_runs::finish_all(&mut app); assert_eq!(undo(&app), steps + 1, "one undo step"); assert_eq!(param(&app, "strokes"), Some(json!(true))); let st = &app.ui.image_trace_panel.shown; diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index d61efcb289..43174d8f9e 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -887,6 +887,7 @@ mod tests { let r = toggle_ref(tag); assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}"); } + // Only an installed face without bundled fonts can offer no set; the rows above are checked. let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); @@ -972,7 +973,9 @@ mod tests { assert_eq!(state_of(&app, &toggle_ref(tag)), Some(toggled(label, false)), "{label}"); run(&mut app, TOGGLE, &json!({"tag": tag})).unwrap().unwrap(); let runs = run_features(&mut app, &id, 8); - assert!(runs.iter().all(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))), "{label}: {runs:?}"); + let tagged: String = + runs.iter().filter(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))).map(|(t, _)| t.as_str()).collect(); + assert_eq!(tagged, "かなAB", "{label}: {runs:?}"); } } @@ -1023,6 +1026,11 @@ mod tests { } } + /// The characters of `runs` ([`metrics_runs`]) whose Proportional Metrics and features `keep` accepts. + fn text_where(runs: &[(String, bool, Vec<String>)], keep: impl Fn(bool, &[String]) -> bool) -> String { + runs.iter().filter(|(_, on, f)| keep(*on, f)).map(|(t, _, _)| t.as_str()).collect() + } + /// Where the panel menu's top-level rows list the command `r`. fn row_index(rows: &[PanelRow], r: &CommandRef) -> Option<usize> { rows.iter().position(|row| matches!(row, PanelRow::Command(c) if c == r)) @@ -1068,13 +1076,14 @@ mod tests { assert_eq!(run(&mut app, METRICS, &json!({})), Some(Ok(json!({"on": true})))); assert_eq!(undo_steps(&app), undo + 1); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); - assert_eq!(runs.iter().map(|(t, _, f)| (t.as_str(), f.clone())).collect::<Vec<_>>(), [("か", vec!["smcp".to_string()]), ("なAB", vec![])]); + assert_eq!(runs, [("か".to_string(), true, vec!["smcp".to_string()]), ("なAB".to_string(), true, vec![])]); assert_eq!(state_of(&app, &metrics), Some(toggled("Proportional Metrics", true))); assert_eq!(run(&mut app, METRICS, &json!({})), Some(Ok(json!({"on": false})))); assert_eq!(undo_steps(&app), undo + 2); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, f)| !*on && (f.is_empty() || *f == ["smcp"])), "{runs:?}"); + assert_eq!(text_where(&runs, |on, _| on), "", "{runs:?}"); + assert_eq!(text_where(&runs, |_, f| f == ["smcp"]), "か", "each run keeps its features: {runs:?}"); + assert_eq!(text_where(&runs, |_, f| f.is_empty()), "なAB", "{runs:?}"); } /// With the Selection tool, Proportional Metrics turns on for the whole selected object. At a @@ -1089,7 +1098,7 @@ mod tests { let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); run(&mut app, METRICS, &json!({})).unwrap().unwrap(); - assert!(metrics_runs(&app, &id).iter().all(|(_, on, _)| *on), "{:?}", metrics_runs(&app, &id)); + assert_eq!(text_where(&metrics_runs(&app, &id), |on, _| on), "かなAB"); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.prefs.show_east_asian_options = true; @@ -1104,7 +1113,7 @@ mod tests { assert_eq!(state_of(&app, &CommandRef::new(METRICS)), Some(toggled("Proportional Metrics", false))); run(&mut app, METRICS, &json!({})).unwrap().unwrap(); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); + assert_eq!(text_where(&runs, |on, _| on), "かなAB", "{runs:?}"); } /// With Real-time Drawing off, Proportional Metrics and H or V Style decide from the text with diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 75310b3f35..8d2ea06ab8 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -282,7 +282,7 @@ fn kinsoku_set_shows_a_custom_set_by_name() { } /// The Mojikumi Set menu lists None, the four other predefined sets and Line-end Punctuation Half -/// Width, each under its own label in every interface language. Each entry sets the selected +/// Width, each under its own label in English and in Japanese. Each entry sets the selected /// paragraphs' set in one undo step and is shown as the current set; paragraphs with different /// sets show a blank menu, and Reset Panel gives them Line-end Punctuation Half Width. #[test] @@ -290,7 +290,7 @@ fn mojikumi_menu_offers_and_sets_every_predefined_set() { let keys: Vec<&str> = mojikumi_sets().iter().map(|s| s.2).collect(); assert_eq!(keys, ["none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku", "lineEndHalf"]); use crate::i18n::LangExt as _; - for lang in crate::i18n::Lang::all() { + for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_code("ja").expect("ja registered")] { crate::i18n::set_current(lang); let labels: std::collections::BTreeSet<&str> = mojikumi_sets().iter().map(|s| s.0).collect(); crate::i18n::set_current(crate::i18n::Lang::EN); @@ -680,10 +680,8 @@ fn the_numbered_list_button_and_its_presets_set_the_list_and_reset_panel_clears_ assert_eq!(lists(&app), (numbered(NumberStyle::Arabic), None), "the caret's paragraph"); assert_eq!(numbers_shown(&app), Some(Some(NumberStyle::Arabic)), "the button shows pressed"); assert_eq!(number_sample(NumberStyle::UpperRoman, 3), "I, II, III"); - for style in NumberStyle::ALL { - set_number_style(&mut app, Some(style)); - assert_eq!(lists(&app), (numbered(style), None), "{}", number_sample(style, 3)); - } + set_number_style(&mut app, Some(NumberStyle::UpperRoman)); + assert_eq!(lists(&app), (numbered(NumberStyle::UpperRoman), None), "a preset picks its style"); set_number_style(&mut app, None); assert_eq!(lists(&app), (None, None)); app.session.set_tool_option("selectAll", &json!(true)); diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 7f71d73da4..0a8ce3b8da 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -903,11 +903,15 @@ mod tests { let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); let (top, bottom) = profile_outline(r, 1.0, Some(&[(0.0, 1.0, 1.0), (0.5, 10.0, 10.0), (1.0, 1.0, 1.0)])); let all: Vec<_> = top.iter().chain(&bottom).collect(); - assert!(all.iter().all(|p| p.y >= r.top() && p.y <= r.bottom()), "{all:?}"); - let middle = all.iter().map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); + let (highest, lowest) = all.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), p| (lo.min(p.y), hi.max(p.y))); + assert!(highest >= r.top() && lowest <= r.bottom(), "the outline stays in its box: {all:?}"); + // How far the outline reaches from the box's middle line. + let reach = |top: &[egui::Pos2], bottom: &[egui::Pos2]| top.iter().chain(bottom).map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); + let middle = reach(&top, &bottom); assert!((middle - (r.height() / 2.0 - 1.0)).abs() < 1e-3, "the widest point fills the box ({middle})"); let (top, bottom) = profile_outline(r, 1.0, None); - assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); + let plain = reach(&top, &bottom); + assert!(plain > 0.0 && plain <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3, "the plain bar keeps its look ({plain})"); } #[test] diff --git a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs index bca7cf7852..06c5ce6caa 100644 --- a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs +++ b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs @@ -23,7 +23,9 @@ fn item_commands_run_on_the_clicked_swatch_and_paint_nothing() { let mut app = app(); select_rows(&mut app, &["Black"]); let (before, paint, undo) = (doc(&app), app.session.paint.fill.clone(), undo_steps(&app)); - assert!(enabled(&app, "Red").iter().all(|(_, on)| *on), "every item is enabled on a user swatch"); + let items = enabled(&app, "Red"); + assert_eq!(items.len(), ITEMS.len(), "{items:?}"); + assert!(items.iter().all(|(_, on)| *on), "every item is enabled on a user swatch: {items:?}"); menu(&mut app, "Red", "options"); assert_eq!(dialog_field(&app, KIND, "name"), json!("Red")); assert_eq!((doc(&app), undo_steps(&app)), (before.clone(), undo), "opening the dialog changes nothing"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 77660aedc2..4397e098e6 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -103,23 +103,21 @@ fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { assert_eq!(ui["ui"]["color_wheel"], with(json!({"view": "box", "channel": "green"}))); } -/// The command's errors are translated in the catalogs that translate status and error messages, -/// and each translation keeps the accepted values. +/// The command's errors are shown in the interface language (German and Japanese here), and each +/// translation keeps the accepted values. #[test] fn ui_color_wheel_errors_are_translated() { let errors = [ ("`view` must be wheel or box", &["wheel", "box"][..]), ("`channel` must be hue, saturation, brightness, red, green or blue", &["hue", "saturation", "brightness", "red", "green", "blue"][..]), ]; - for code in [ - "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", - "ca", "nl", "bs", "da", "id", - ] { + for code in ["de", "ja"] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); for (error, values) in errors { let shown = crate::i18n::message(lang, error); assert_ne!(shown, error, "{code}"); - assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + let missing: Vec<&str> = values.iter().copied().filter(|v| !shown.contains(v)).collect(); + assert!(missing.is_empty(), "{code}: {shown} lacks {missing:?}"); } } } @@ -147,16 +145,6 @@ fn ui_color_wheel_rejects_other_params() { assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } -/// `ui.colorWheel` answers every junk parameter without a panic. -#[test] -fn ui_color_wheel_answers_junk_params_without_a_panic() { - let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; - let mut app = app(json!("#336699"), "hue"); - for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { - let _ = app.run("ui.colorWheel", p); - } -} - /// The settings survive a JSON round trip of the preferences, and a saved value this build does /// not know reads as the key's default without losing the other preferences. #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index 230485922f..b19877ec58 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -38,44 +38,20 @@ fn uncalibrated_cmyk_marks_nothing() { }); } -/// A profile loaded again under the same name can change which colors are printable while the -/// color settings stay the same; the panel keeps drawing through the change. +/// In the wheel's square and in the box, Show Out-of-Gamut Colors changes what the panel draws, +/// and turning it off again draws the panel as it was. #[test] -fn the_grid_is_computed_again_after_a_profile_is_loaded() { - if !crate::testing::in_own_process("panels::tests_color_wheel_gamut::the_grid_is_computed_again_after_a_profile_is_loaded") { - return; +fn the_setting_shades_the_wheel_and_the_box() { + for view in ["wheel", "box"] { + let mut p = Panel::new(app("#3366cc", view, false)); + let off = p.fx.frame_shapes(); + p.run("ui.colorWheel", json!({"gamut": true})); + let on = p.fx.frame_shapes(); + // Compared without printing: a frame holds thousands of shapes. + assert!(on != off, "{view}: the shading is drawn"); + p.run("ui.colorWheel", json!({"gamut": false})); + assert!(p.fx.frame_shapes() == off, "{view}: off draws no shading"); } - let mut p = Panel::new(app("#3366cc", "box", true)); - /// Unregisters the profile when dropped, also after a failed assertion. - struct Unregister(&'static str); - impl Drop for Unregister { - fn drop(&mut self) { - cms::unregister_icc(self.0); - } - } - let name = "Color Wheel Gamut Reload CMYK"; - let bytes = cms::icc_bytes(cms::GENERIC_CMYK).unwrap(); - cms::register_icc(&bytes, Some(name.into())).unwrap(); - let _unregister = Unregister(name); - p.fx.idle(2); - assert!(p.fx.by_label("Color box").is_some()); -} - -/// The wheel's square and the Hue box both show with the setting on. -#[test] -fn the_wheel_and_the_hue_box_shade_the_same_cells() { - let mut p = Panel::new(app("#3366cc", "wheel", true)); - assert!(p.fx.by_label("Saturation and brightness").is_some()); - p.run("ui.colorWheel", json!({"view": "box"})); - assert!(p.fx.by_label("Color box").is_some()); -} - -/// With Show Out-of-Gamut Colors off, the panel still draws and the setting reads off. -#[test] -fn with_the_setting_off_no_grid_is_computed() { - let p = Panel::new(app("#3366cc", "box", false)); - assert!(!p.app().ui.color_wheel.gamut); - assert!(p.fx.by_label("Color box").is_some()); } /// `ui.colorWheel {gamut}` sets the setting and keeps the others; a key set to null keeps its value diff --git a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs index 8a8ddf4768..be2cf16ae3 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs @@ -114,17 +114,14 @@ fn ui_color_wheel_sets_the_harmony_and_its_rule() { assert_eq!(got["harmonyRule"], json!("splitComplementary")); } -/// The errors are translated in the catalogs that translate status and error messages, and each +/// The errors are shown in the interface language (German and Japanese here), and each /// translation keeps the key and the accepted values. #[test] fn ui_color_wheel_harmony_errors_are_translated() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let flag = app.run("ui.colorWheel", json!({"harmony": 1})).unwrap_err(); let rule = app.run("ui.colorWheel", json!({"harmonyRule": "shades"})).unwrap_err(); - for code in [ - "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", - "ca", "nl", "bs", "da", "id", - ] { + for code in ["de", "ja"] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); let shown = crate::i18n::message(lang, &flag); assert!(shown != flag && shown.contains("`harmony`"), "{code}: {shown}"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index f3b5ca6a47..58cb9a84b4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -433,14 +433,3 @@ fn the_row_is_gray_with_nothing_selected_and_on_type() { let p = Panel::new(app); assert!(disabled(&p)); } - -/// `ui.colorWheel` answers every junk parameter, with and without a document, without a panic. -#[test] -fn ui_color_wheel_answers_junk_params_without_a_panic() { - let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; - for mut app in [app(), VectorcraftApp::new(Session::new(), Default::default())] { - for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { - let _ = app.run("ui.colorWheel", p); - } - } -} diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index c554b21add..183d7bbe7e 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -153,15 +153,30 @@ pub fn poll(app: &mut VectorcraftApp) { } Err(TryRecvError::Disconnected) => None, }; - let r = app.trace_runs.running.remove(i); - // The status bar no longer says it is tracing. - if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { - app.ui.status.clear(); - } - finish(app, r, done); + land(app, i, done); } } +/// Waits for each trace running to end, in the order they were started, and applies it as +/// [`poll`] does once it is done. +#[cfg(test)] +pub(crate) fn finish_all(app: &mut VectorcraftApp) { + while let Some(r) = app.trace_runs.running.first() { + let done = r.done.recv().ok(); + land(app, 0, done); + } +} + +/// Takes trace `i`, which has ended with `done`, off the list and applies it. +fn land(app: &mut VectorcraftApp, i: usize, done: Option<Done>) { + let r = app.trace_runs.running.remove(i); + // The status bar no longer says it is tracing. + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + /// Applies trace `r`'s result in its document, which becomes the active one again, as its command /// would while the object, its image and the settings are as they were and the document was not /// reverted; else why it has none, in the status bar. From c6662b1f24b8aae5f9043a1c1a6dd73ff6d93cf3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:42:49 -0800 Subject: [PATCH 68/71] Tests: presets_resolve checks every listed preset name resolves `presets()` leaves out a name that `preset` does not know, so the test now compares its length with `PRESET_NAMES` and checks that list holds 15 names, in place of a fixed count of 15 resolved presets. --- crates/trace/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index a461978600..b834ea4b4a 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -913,7 +913,8 @@ fn snap_curves_to_lines_straightens_near_lines() { #[test] fn presets_resolve() { // Every name resolves: `presets` leaves out a name `preset` does not know. - assert_eq!(presets().len(), 15); + assert_eq!(PRESET_NAMES.len(), 15); + assert_eq!(presets().len(), PRESET_NAMES.len()); assert_eq!(preset("[Default]"), preset("Default")); assert_eq!(preset(" Line Art "), preset("line art")); assert_eq!(preset("16 colors").unwrap().colors, 16); From 771e73d4056199bb9721206338eefc8a5a936c41 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:47:59 -0800 Subject: [PATCH 69/71] Tests: Hebrew mark clusters must cover the whole word hebrew_marks_stay_with_base_clusters now calls assert_source_coverage, so glyphs that start at the four letters but leave the marks out of their source ranges fail the test. --- crates/text/src/tests/bidi.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index 4a761dda20..68fb50f4ec 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -257,9 +257,7 @@ fn hebrew_marks_stay_with_base_clusters() { // Each glyph's source starts at one of the four letters, never at a point after one. let starts: std::collections::BTreeSet<usize> = l.glyphs.iter().map(|g| g.byte).collect(); assert_eq!(starts, [0, 6, 8, 12].into(), "{:?}", l.glyphs.iter().map(|g| (g.byte, g.len)).collect::<Vec<_>>()); - for g in &l.glyphs { - assert!(s.get(g.byte..g.byte + g.len).is_some()); - } + assert_source_coverage(s, &l); assert!(l.glyphs.iter().all(|g| g.rtl)); } From 5071f17319e719d98f6b60a8d7221f4722810fa3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 1 Dec 2026 17:53:19 -0800 Subject: [PATCH 70/71] Tests: skip the Hebrew mark cluster test when no font covers Hebrew hebrew_marks_stay_with_base_clusters asserts exact glyph start offsets, which depend on the face that shapes the word. It now skips, as the sibling font-dependent tests do, when no installed face covers shin, lamed, vav and final mem. --- crates/text/src/tests/bidi.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index 68fb50f4ec..bf47f56d5a 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -253,6 +253,10 @@ fn paragraph_direction_is_independent_and_neutrals_do_not_force_ltr() { #[test] fn hebrew_marks_stay_with_base_clusters() { let s = "שָׁלוֹם"; + if FontDb::global().face_covering('ש').is_none_or(|face| !['ל', 'ו', 'ם'].into_iter().all(|c| face.covers(c))) { + eprintln!("SKIPPED: hebrew_marks_stay_with_base_clusters; no installed font covers Hebrew shin, lamed, vav and final mem"); + return; + } let l = text_layout(s); // Each glyph's source starts at one of the four letters, never at a point after one. let starts: std::collections::BTreeSet<usize> = l.glyphs.iter().map(|g| g.byte).collect(); From 450a821ae4dfc2bc75123ec6bef7ccf0ec8f96bf Mon Sep 17 00:00:00 2001 From: ruchirguitar <info@jeevantirth.org> Date: Wed, 2 Dec 2026 07:35:21 +0530 Subject: [PATCH 71/71] .ai import: say where unchecked page type over hidden type goes --- crates/eps/src/import/native/plan.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index a15c272222..f2dfba3377 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -556,7 +556,9 @@ pub(super) fn plan( let mut spare: Vec<Vec<Arc<Node>>> = vec![]; // The word searches below are held to their own budget: past it, type where made type that shows // draws is taken to be that type (made type is there either way), and type where only made type - // that doesn't show lies stays on the page (it would not show otherwise). + // that doesn't show lies is spare type, as any type no text object takes: it goes into a slot + // or with another text object's type, else it is left out with a note (taken as the hidden + // type, it would be dropped unnoted). let (mut checks, mut unchecked) = (WordChecks::new(), false); for (j, object) in shown.iter().enumerate() { match owner.get(j).copied().flatten() {